我正在使用SQLAlchemy并尝试管理与“预订”具有多对一关系的“媒体”模型。在scoped_session.delete()
事件中呼叫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)
答案 0 :(得分:1)
使用session.execute(“delete ...”)或session.query(cls).delete()的mass delete()应该没问题,它只是在当前连接上发出SQL。
就session.delete(obj)而言,看起来在最终的flush()之前调用了before_commit(),所以在这种意义上你可以把它当作before_flush()事件来对待它。尝试一下,你应该看到发出DELETE,如果是,那你就没事了。