SQLAlchemy - Get and delete object

These are some utility methods to make a query with SQLAlchemy: I gonna use the MyDatabaseConnector class from the previous blog post:


db = MyDatabaseConnector()

* Get object:

def get_obj(db, pk):
session = db.get_session()
try:
obj = session.query(MyObjModel).get(pk)
except:
print "Object not found"
finally:
session.commit()
db.close()

* Delete object:

def delete_obj(db, pk):
session = db.get_session()
try:
obj = session.query(MyObjModel).get(pk)
except:
print "Object not found"
else:
session.delete(obj)
finally:
session.commit()
db.close()


Reference: http://docs.sqlalchemy.org/en/rel_0_9/orm/query.html

Comments