Sqlalchemy事件监听器和关系问题

发布于 2024-11-19 03:17:19 字数 1007 浏览 2 评论 0原文

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

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

秋千易 2024-11-26 03:17:19

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 the append event will fire your handler whether you append to the downlines or set the upline of a Distributor instance.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文