リレーションモデルでイベントリスナーを使用する際に問題があります。モデルクラスは自己参照テーブルです。
class Distributor(Base):
__tablename__ = "distributors"
id = Column(Integer, primary_key=True)
name = Column(String, nullable = False)
upline_id = Column(Integer, ForeignKey('distributors.id'))
upline = relationship('Distributor', remote_side=id, backref=backref('downlines'))
そして、ダウンラインコレクションに追加するイベントでリスナーを登録しようとしています。
def my_append_listener(target, value, initiator):
branch_develop = len(target.downlines)
そしてこの行:
event.listen(Distributor.downlines, 'append', my_append_listener)
エラーが発生します:AttributeError:type object'Distributor' has no attribute'downlines'
しかし、次のように書くことは問題ありません。
george = Distributor("george", None)
george.downlines = [Distributor("downlineUser")]
また、関係をこれに書き直すと、次のことがわかりました。
downlines = relationship('Distributor', backref=backref('upline', remote_side=id))
すべてが完璧に実行されます。誰かがコードの何が問題なのか教えてもらえますか?