axon
axon

Reputation: 678

SQLAlchemy Event interface

I'm using SQLAlchemy 0.7. I would like some 'post-processing' to occur after a session.flush(), namely, I need to access the instances involved in the flush() and iterate through them. The flush() call will update the database, but the instances involved also store some data in an LDAP database, I would like SQLAlchemy to trigger an update to that LDAP database by calling an instance method.

I figured I'd be using the after_flush(session, flush_context) event, detailed here, but how do I get a list of update()'d instances?

On a side note, how can I determine which columns have changed (or are 'dirty') on an instance. I've been able to find out if an instance as a whole is dirty, but not individual properties.

Upvotes: 4

Views: 1232

Answers (1)

shazow
shazow

Reputation: 18197

According to the link you provided:

Note that the session’s state is still in pre-flush, i.e. ‘new’, ‘dirty’, and ‘deleted’ lists still show pre-flush state as well as the history settings on instance attributes.

This means that you should be able to get an access of all the dirty objects in the session.dirty list. You'll note that the first parameter of the event callback is the current session object.

As for the second part, you can use the sqlalchemy.orm.attributes.get_history function to figure out which columns have been changed. It returns a History object for a given attribute which contains a has_changes() method.

If you're trying to listen for changes on specific class attributes, consider using Attribute Events instead.

Upvotes: 4

Related Questions