Skip to content

Instantly share code, notes, and snippets.

@jleclanche
Created July 7, 2017 09:57
Show Gist options
  • Save jleclanche/f53ab91184632d717b228ec782d36dd8 to your computer and use it in GitHub Desktop.
Save jleclanche/f53ab91184632d717b228ec782d36dd8 to your computer and use it in GitHub Desktop.
SQLAlchemy get or create
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
@Greyvend
Copy link

Greyvend commented Feb 23, 2021

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.

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