On May 26, 2010, at 12:18 AM, Dan Ellis wrote:

> 
> class EventExtension(SessionExtension):
>    def __init__(self):
>        self.new = []
> 
>    def after_flush(self, session, flush_context):
>        self.new = session.new
>        return EXT_CONTINUE
> 
>    def after_commit(self, session):
>        for instance in self.new:
>            fire_event('model/create/%s' %
> instance.__class__.__name__, instance)
>        self.new = []
>        return EXT_CONTINUE
> 
> The reason for the __init__ method is that after_commit was being
> called without after_flush having been called, because I was calling
> session.commit() after processing every request, or session.rollback()
> if an exception was thrown. Perhaps autocommit would suit me better.

but if after_commit() is called and after_flush() is not called, that means 
nothing was flushed.   

Usually the way to go about this is to populate a distinct collection of events 
when objects are created:


foo = MyObject()
Session.add(foo)
add_commit_event(some_callable)

where add_commit_event:

def add_commit_event(task):
    session = Session()
    if not hasattr(session, '_after_commit_tasks'):
        tasks = session._after_commit_tasks = []
    else:
        tasks = session._after_commit_tasks
    tasks.append(task)

the session extension then pops from _after_commit_tasks.

> The problem I have is that the newly created Story doesn't have its
> relationship attributes populated. For example, author_id==1, but
> author==None. This particularly confuses me because the docs say that
> relations are lazily loaded by default.

the ORM is not going to help you much if you directly populate foreign key 
identifiers instead of the corresponding relationship() attributes (this is in 
the FAQ).   Once the commit is complete, all objects are expired by default, so 
that when you go to reach foo.author it will reload from the DB.    You can 
expire the attribute manually ahead of time if you want it to reload its value 
(should be fine within after_commit).

-- 
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To post to this group, send email to sqlalch...@googlegroups.com.
To unsubscribe from this group, send email to 
sqlalchemy+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en.

Reply via email to