tags:

views:

33

answers:

2

I want to write a SessionExtension that fires a 'Foo-created' event or 'Bar-created' event every time a new Foo or new Bar is committed to the database. However, once inside the after_commit method, I don't know where to find which entities have been committed. Where do I get this information?

+2  A: 

The Session instance has attribute new, dirty, deleted holding added, updated and deleted objects respectively. They will be already empty when after_commit is executed, but they are available in after_flush. You can extent your own list of added instances for each flush in after_flush hook and use them for events and clear in after_commit.

Denis Otkidach
Okay, so I copy `new` in `after_flush` and then use that in `after_commit`? Sounds simple enough. Thanks!
Dan Ellis
Okay, but the problem I then have is that the newly-created instance doesn't have its relationship attributes set. For example, `author_id` is an integer, but `author` is `None`. Is there some better way to fix that than making the relationship lazy, which would be a bit leaky?
Dan Ellis
I just checked, and relationships are lazily loaded by default anyway, so I'm not sure what to do. Might have to go to the mailing list for this one.
Dan Ellis
A: 

Look at the Mapper Extension bits. It provides you before/after insert/update/delete hooks that you can place your code for this kind of thing.

http://www.sqlalchemy.org/docs/mappers.html?highlight=mapper%20extension#extending-mapper

Rick
Yes, but the problem there is that they might not make it into the database, for any number of reasons.
Dan Ellis