get_or_create.py 469 B

1234567891011121314
  1. def get_or_create(session, model, **kwargs):
  2. """
  3. Creates an object or returns the object if exists
  4. credit to Kevin @ StackOverflow
  5. from: http://stackoverflow.com/questions/2546207/does-sqlalchemy-have-an-equivalent-of-djangos-get-or-create
  6. """
  7. instance = session.query(model).filter_by(**kwargs).first()
  8. if instance:
  9. return instance
  10. else:
  11. instance = model(**kwargs)
  12. session.add(instance)
  13. return instance