Created
July 7, 2017 09:57
-
-
Save jleclanche/f53ab91184632d717b228ec782d36dd8 to your computer and use it in GitHub Desktop.
SQLAlchemy get or create
This file contains hidden or 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
def get_or_create(session, model, defaults=None, **kwargs): | |
""" | |
Get or create a model instance while preserving integrity. | |
""" | |
try: | |
return session.query(model).filter_by(**kwargs).one(), False | |
except NoResultFound: | |
if defaults is not None: | |
kwargs.update(defaults) | |
try: | |
with session.begin_nested(): | |
instance = model(**kwargs) | |
session.add(instance) | |
return instance, True | |
except IntegrityError: | |
return session.query(model).filter_by(**kwargs).one(), False | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You don't need
begin_nested
block here, since there's just one write operation being made. Instead,session.commit()
after L14 would do it.Commit is needed for changes to be persisted in DB, and
id
to be available in the instance.