我正在尝试为我的一些表添加审核日志记录,这是我在after_flush
侦听器中实现的。通过访问session.new
/ dirty
/ deleted
中的会话状态,我可以获得所需的信息。
嗯,至少在大多数情况下:我没有运气识别通过“删除孤儿”级联删除的实例。这些实例不会显示在session.deleted
中,而是显示在session.dirty
中,我找不到确定是否会删除它们的方法。
使用这个玩具模型来说明:
class Author(Base):
__tablename__ = 'authors'
id = Column(Integer, primary_key=True)
name = Column(String)
posts = relationship('Post', back_populates='author', cascade='all, delete-orphan')
def __repr__(self):
return 'Author(name={0.name})'.format(self)
class Post(Base):
__tablename__ = 'posts'
id = Column(Integer, primary_key=True)
content = Column(String)
author_id = Column(Integer, ForeignKey('authors.id'))
author = relationship('Author', back_populates='posts')
def __repr__(self):
return 'Post(content={0.content})'.format(self)
识别常规添加/更新/删除按预期工作:
In [1]: session = Session()
...: jane = Author(name='Jane')
...: jane.posts = [Post(content='The nature of things'), Post(content='On the origin of stuff')]
...: session.add(jane)
...: session.new
Out[1]: IdentitySet([Author(name=Jane), Post(content=On the origin of stuff), Post(content=The nature of things)])
In [2]: session.flush()
...: jane.name = 'John'
...: session.dirty
Out[2]: IdentitySet([Author(name=John)])
In [3]: session.flush()
...: post = jane.posts[0]
...: session.delete(post)
...: session.deleted
Out[3]: IdentitySet([Post(content=The nature of things)])
到目前为止一切顺利。但是,当我通过关系更新作者的帖子,导致“东西的来源”帖子通过级联删除时,这个消除的帖子只显示为脏,而不是删除:
In [4]: session.flush()
...: jane.posts = [Post(content='Matter matters!')]
...: session.deleted
Out[4]: IdentitySet([])
In [5]: session.dirty
Out[5]: IdentitySet([Author(name=Jane), Post(content=On the origin of stuff)])
我怎样才能检测到这个帖子会被删除(或者在after_flush
监听器的情况下)?