On Aug 26, 2014, at 2:35 PM, Chad Dombrova <[email protected]> wrote:
> @event.listens_for(Session, 'after_flush_postexec') > def after_flush_postexec(session, flush_context): > print "-" * 40 > > for state in flush_context.states: > print state.object > > for at in state.attrs: > history = flush_context.get_attribute_history(state, at.key) > added, unchanged, deleted = history > > if added: > print " added:", at.key, [x.object for x in added] > > def test(): > Base.metadata.create_all(engine) > > book = Book(title='sqlalchemy for dummies') > session = Session() > session.add(book) > session.commit() > > john = Author(name='John Doe') > jane = Author(name='Jane Doe') > book.authors = [john, jane] > book2 = Book(title='sqlalchemy pro tips') > book2.authors = [john] > session.add(book2) > session.commit() > > this prints: > > ---------------------------------------- > Book(1) > ---------------------------------------- > Book(2) > added: authors [Author(1)] > Author(2) > added: books [Book(1)] > Book(1) > added: authors [Author(1), Author(2)] > Author(1) > added: books [Book(1), Book(2)] > > > when the event runs after the second commit, how can I tell that Book(2) was > inserted and Book(1) was not? after_flush_postexec() runs after the history of the Session has been cleared, so it can't be used for this purpose. Instead, you'd use after_flush(). Within this event, you can discern that an object was an INSERT or not based on if it is present in the session.new collection. -- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to [email protected]. To post to this group, send email to [email protected]. Visit this group at http://groups.google.com/group/sqlalchemy. For more options, visit https://groups.google.com/d/optout.
