2014-01-27 183 views
0

我正在使用SQLAlchemy并尝试管理与“预订”具有多对一关系的模型“媒体”。从before_commit事件中拨打scoped_session.delete()安全吗?无论是使用session.executeSQLAlchemy删除before_commit安全吗?

def before_commit(session): 
    r""" Invokes the ``before_commit`` method on all items in the session. 
    This allows the models to perform an update-action depending on their 
    new data. """ 

    for item in session.deleted: 
     if hasattr(item, 'before_commit'): 
      item.before_commit(session, 'deleted') 

    for item in session.dirty: 
     if hasattr(item, 'before_commit'): 
      item.before_commit(session, 'dirty') 

    for item in session.new: 
     if hasattr(item, 'before_commit'): 
      item.before_commit(session, 'new') 

event.listen(db.session.__class__, 'before_commit', before_commit) 

class Booking(db.Model): 

    # ... 

    media = db.relationship(Media, backref='booking') 

    def before_commit(self, session, status): 
     r""" Validates the booking's data. If the booking is being deleted, 
     all its media will be deleted with it. """ 

     if status == 'deleted': 
      # Delete all the media that is associated with this booking. 
      for media in self.media: 
       session.delete(media) 

回答

1

一个批量删除()( “删除...”)或session.query(CLS).delete()应该罚款,它只是发出当前连接上SQL。

就session.delete(obj)而言,它看起来像before_commit()在final flush()之前被调用,所以在这种意义上,你可以像before_flush()事件那样对待它。试试看,你应该看到DELETE正在发射,如果是这样,那么你很好。