Skip to content

Instantly share code, notes, and snippets.

@treethought
Created March 30, 2017 06:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save treethought/70a873806e66abed7217a6d460718582 to your computer and use it in GitHub Desktop.
Save treethought/70a873806e66abed7217a6d460718582 to your computer and use it in GitHub Desktop.
Get or create an object with SQLAlchemy
# http://stackoverflow.com/questions/2546207/does-sqlalchemy-have-an-equivalent-of-djangos-get-or-create
# credit to Wolf
def get_or_create(session, model, defaults=None, **kwargs):
instance = session.query(model).filter_by(**kwargs).first()
if instance:
return instance, False
else:
params = dict((k, v) for k, v in kwargs.iteritems() if not isinstance(v, ClauseElement))
params.update(defaults or {})
instance = model(**params)
session.add(instance)
return instance, True
# credit to skytreader and Kevin.
def get_or_create_simple(session, model, **kwargs):
instance = session.query(model).filter_by(**kwargs).first()
if instance:
return instance
else:
instance = model(**kwargs)
session.add(instance)
session.commit()
return instance
@nawarazpokhrel
Copy link

I am unable to import session I got this
AttributeError: 'sessionmaker' object has no attribute 'query'

@treethought
Copy link
Author

I'm sorry it's been a while since I made this or used sqlalchemy. I would guess there have been changes in sqlalchemy that make this incorrect

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment