Sqlalchemy事件侦听器和关系问题

Sqlalchemy事件侦听器和关系问题,sqlalchemy,self-reference,Sqlalchemy,Self Reference,我在将事件侦听器与关系模型一起使用时遇到问题,我的模型类是一个自引用表: class Distributor(Base): __tablename__ = "distributors" id = Column(Integer, primary_key=True) name = Column(String, nullable = False) upline_id = Column(Integer, ForeignKey('distributors.id'))

我在将事件侦听器与关系模型一起使用时遇到问题,我的模型类是一个自引用表:

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)
will给出错误:AttributeError:type对象“Distributor”没有属性“downlines”

但可以写下这样的内容:

george = Distributor("george", None)
george.downlines = [Distributor("downlineUser")]
我还发现,如果我重写与此的关系:

downlines = relationship('Distributor', backref=backref('upline', remote_side=id))

一切运转正常。有人能告诉我代码中有什么错误吗?

下线backref仅作为分销商模型实例上的一个属性存在。它不是用作侦听器目标的模型定义的属性

幸运的是,将侦听器设置在哪一边没有多大区别。在父级(
downlines
)上定义关系并侦听
append
事件将触发处理程序,无论您是追加到分发服务器实例的
downlines
还是设置
上线