Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine which fields are dirty on an SQLAlchemy object

I know that, using SQLAlchemy's session object I can call session.dirty to get all objects with changes that need to be committed to the database. But how can I determine which specific fields on any one object are dirty? Is there a method I can call on the specific object that returns these fields? Or maybe I can pass the object into one of session's class methods to get this?

like image 932
J-bob Avatar asked Feb 05 '15 20:02

J-bob


1 Answers

An example from the History class:

from sqlalchemy import inspect

hist = inspect(myobject).attrs.myattribute.history

If you wanted to check all defined attributes for a given object instance, you probably could do something like this:

def print_changes(myobj):
    from sqlalchemy.orm import class_mapper
    from sqlalchemy import inspect
    inspr = inspect(myobj)
    attrs = class_mapper(myobj.__class__).column_attrs  # exclude relationships
    for attr in attrs:
        hist = getattr(inspr.attrs, attr.key).history
        print(attr.key, hist.has_changes())
like image 133
van Avatar answered Oct 18 '22 17:10

van