Skip to content

Instantly share code, notes, and snippets.

@jangeador
Last active December 6, 2023 04:57
Show Gist options
  • Save jangeador/e7221fc3b5ebeeac9a08 to your computer and use it in GitHub Desktop.
Save jangeador/e7221fc3b5ebeeac9a08 to your computer and use it in GitHub Desktop.
A function that creates unique objects based on models
def get_or_create(session, model, **kwargs):
'''
Creates an object or returns the object if exists
credit to Kevin @ StackOverflow
from: http://stackoverflow.com/questions/2546207/does-sqlalchemy-have-an-equivalent-of-djangos-get-or-create
'''
instance = session.query(model).filter_by(**kwargs).first()
if instance:
return instance
else:
instance = model(**kwargs)
session.add(instance)
return instance
# Usage:
# Suppose my model object is :
class Country(Base):
__tablename__ = 'countries'
id = Column(Integer, primary_key=True)
name = Column(String, unique=True)
# To get or create my object I write :
myCountry = get_or_create(session, Country, name=countryName)
@jakubblaha-ids
Copy link

Change

if ...:
    ...
    return ...
else:
    ...
    return ...

to

if ...:
    ...
    return ...

return ...

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