after_delete callback doesn't being called with query(...).delete() syntax

507 views
Skip to first unread message

Igor Loskutoff

unread,
Mar 24, 2014, 9:05:53 AM3/24/14
to sqlal...@googlegroups.com
Hey, 

I'm faced issue with after_delete callback call. 
It works when I do

y = DBSession.query(Yarns).filter_by(user_id=user.id, slug=yarn_id).first()
    DBSession.delete(y)
    DBSession.flush()

and doesn't being called on 

DBSession.query(Yarns).filter_by(user_id=user.id, slug=yarn_id).delete() 
 
where DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))

Callback itself is being set like that: sqlalchemy.event.listen(Yarns, 'after_delete', yarn_index_remove)

Model class looks like that:

class Yarns(sqlalchemy.ext.declarative.declarative_base()):  
...

I'd really like use more succinct first syntax instead of current.

Thanks,
Igor

Simon King

unread,
Mar 24, 2014, 9:21:56 AM3/24/14
to sqlal...@googlegroups.com
I think the problem is that after_delete is only used for instances
which have actually been loaded from the DB. Query.delete() doesn't
load the matching rows from the DB, so the event doesn't fire.

There is also a (session, rather than mapper) event called
"after_bulk_delete" which you might be able to use:

http://docs.sqlalchemy.org/en/rel_0_9/orm/events.html#sqlalchemy.orm.events.SessionEvents.after_bulk_delete

You'd probably have to examine the delete_context.query object to see
which class is being deleted, and figuring out exactly which rows have
been deleted might also be a problem (since the filter conditions
passed to the query could be arbitrarily complicated).

Simon

Michael Bayer

unread,
Mar 24, 2014, 9:38:57 AM3/24/14
to sqlal...@googlegroups.com
“after_delete” is only called for unit-of-work deletes.   The aggregate delete() doesn’t have the same access to object instances that the UOW does as it may match any number (or no) objects, none of which may be locally present.  To catch those events use after_bulk_delete().




.

Thanks,
Igor

--
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 sqlalchemy+...@googlegroups.com.
To post to this group, send email to sqlal...@googlegroups.com.
Visit this group at http://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages