Created
March 30, 2017 06:48
-
-
Save treethought/70a873806e66abed7217a6d460718582 to your computer and use it in GitHub Desktop.
Get or create an object with SQLAlchemy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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