How to elegantly check the existence of an object/instance/variable and simultaneously assign it to variable if it exists in python?
You want to execute a Exist query to be efficient
(ret, ), = Session.query(exists().where(SomeObject.field==value))
Mike Bayer explain it in his blog post:
http://techspot.zzzeek.org/2008/09/09/selecting-booleans/
You can use scalar if you don't want to have a tuple as result:
ret = Session.query(exists().where(SomeObject.field==value)).scalar()
This has been asked a long time ago but for future visitors a more concise way to check is
if session.query(model).filter(some_filter).count():
# do stuff
wrap it on a function (shamelessly stolen from django get_or_create, this doesnt return a tuple though)
get_or_create(model, **kwargs):
try:
# basically check the obj from the db, this syntax might be wrong
object = session.query(model).filter(**kwargs).first()
return object
except DoesNotExistException: # or whatever error/exception it is on SQLA
object = model()
# do it here if you want to save the obj to the db
return object
that's it. to use it:
obj = get_or_create(SomeObject, filters)
change the **kwargs
to a simple argument (like some_filters) if you want
try to wrap something you often use (wrap them to functions or classes)
thats only pseudo code, there might be syntax error.
EDIT: emphasize