1

我正在尝试为我在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听众的情况下已被删除)?

4

0 回答 0