Sqlalchemy事件监听器和关系问题
我在关系模型中使用事件侦听器时遇到问题,我的模型类是一个自引用表:
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))
一切都会完美运行。有人可以告诉我代码有什么问题吗?
I have a problem of using event listener with the relation model, my model class is a self referenced table:
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'))
and I'm tring to register a listener on the event of adding to the downlines collection:
def my_append_listener(target, value, initiator):
branch_develop = len(target.downlines)
and this line:
event.listen(Distributor.downlines, 'append', my_append_listener)
will gives an error: AttributeError: type object 'Distributor' has no attribute 'downlines'
but it is ok to write something like:
george = Distributor("george", None)
george.downlines = [Distributor("downlineUser")]
and I also found that if I rewrite the relationship to this:
downlines = relationship('Distributor', backref=backref('upline', remote_side=id))
everything runs perfectly. Could someone tell me what's wrong in the code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
downlines
backref 仅作为 Distributor 模型实例上的属性存在。它不是用作侦听器目标的模型定义的属性。幸运的是,将监听器设置在哪一侧并没有太大区别。在父级 (
downlines
) 上定义关系并侦听append
事件将触发您的处理程序,无论您追加到downlines
还是设置 <分发服务器实例的 code>upline。The
downlines
backref only exists as an attribute on an instance of the Distributor model. It is not an attribute of the model definition which you use as the target for your listener.Fortunately, it doesn't make much difference which side you set the listener on. Defining the relationship on the parent (
downlines
) and listening for theappend
event will fire your handler whether you append to thedownlines
or set theupline
of a Distributor instance.