开发者

Sqlalchemy event listener and relation issue

开发者 https://www.devze.com 2023-03-18 22:07 出处:网络
I have a problem of using event listener with the relation model, my model class is a self referenced table:

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 t开发者_如何学Pythono 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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消