after_flush
リスナーに実装したいくつかのテーブルに監査ログを追加しようとしています。session.new
//でセッション状態にアクセスすることで、必要な情報を取得できますdirty
。deleted
まあ、少なくともほとんどの場合: 「delete-orphan」カスケードを介して削除されるインスタンスを特定することはできません。これらのインスタンスは に表示されませんが、 に表示され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
リスナーの場合は削除された) ことをどのように検出できますか?