【发布时间】:2011-07-07 19:32:26
【问题描述】:
我在使用关系模型的事件监听器时遇到问题,我的模型类是一个自引用表:
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))
一切运行完美。有人能告诉我代码有什么问题吗?
【问题讨论】: