如何检测何时通过“删除孤立”级联删除实例?

时间:2016-09-30 13:11:11

标签: python sqlalchemy all-delete-orphan

我正在尝试为我的一些表添加审核日志记录,这是我在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监听器的情况下)?

0 个答案:

没有答案