Search code examples
pythonmysqlpython-2.7sqlalchemypyramid

Detect if a SQLAlchemy model has pending write operations associated with it


I have an application in which I query against a SQL database and end up with a SQL Alchemy object representing a given row. Then, based on user input and a series of if/then statements I may perform an update on the SQLA object.

i.e.,

if 'fooinput1' in payload:
   sqla_instance.foo1 = validate_foo1(fooinput1)
if 'fooinput2' in payload:
   sqla_instance.foo2 = validate_foo2(fooinput2)
...

I now need to add modified_at and modified_by data to this system. Is it possible to check something on the SQLA instance like sqla_instance.was_modified or sqla_instance.update_pending to determine if a modification was performed?

(I recognize that I could maintain my own was_modified boolean, but since there are many of these if/then clauses that would lead to a lot of boilerplate which I'd like to avoid if possible.)


FWIW: this is a python 2.7 pyramids app reading from a MySQL db in the context of a web request.


Solution

  • The Session object SQL Alchemy ORM provides has two attributes that can help with what you are trying to do:

    1) Session.is_modified()

    2) Session.dirty