我在将事件侦听器与关系模型一起使用时遇到问题,我的模型类是一个自引用表:
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))
一切运行完美。有人能告诉我代码有什么问题吗?