Sqlalchemy - access results of `before_update` during the transaction

Viewed 50

I've got some classes which have a version number that gets incremented on each update via a before_update event, roughly as follows:

listen(MyClass, 'before_update', increment_version)

def increment_version(mapper,connect,target):
    target.version += 1

I now want to store in a different type of object which version of a MyClass object operated on it.

Something like:

my_obj.update_some_fields() 
session.add(my_obj) # when before_update occurs, this object's version number will increment
my_other_obj.update_some_fields_based_on_my_obj()
my_other_obj.relevant_version = my_obj.version # I want this to have my_obj's new version number
session.add(my_other_obj)

When this session is committed, the version number on my_obj gets incremented, but the relevant_version field on my_other_obj is my_obj's previous version number.

I need the changes to both my_obj and my_other_obj to happen within the same transaction.

How can I access the results of before_update triggers within the transaction?

1 Answers

Use session.flush() during the transaction. This will ensure the callbacks get called, e.g.

my_obj.update_some_fields() 
session.add(my_obj) # when before_update occurs, this object's version number will increment
session.flush()
my_other_obj.update_some_fields_based_on_my_obj()
my_other_obj.relevant_version = my_obj.version # I want this to have my_obj's new version number
session.add(my_other_obj)
Related