Many-to-many self-referential relationship in sqlalchemy

微笑、不失礼 提交于 2019-12-09 14:47:31

问题


I'm trying to make a self-referential many-to-many relationship (it means that Line can have many parent lines and many child lines) in sqlalchemy like this:

Base = declarative_base()

class Association(Base):
 __tablename__ = 'association'

 prev_id = Column(Integer, ForeignKey('line.id'), primary_key=True)                            
 next_id = Column(Integer, ForeignKey('line.id'), primary_key=True)


class Line(Base):
 __tablename__ = 'line'

 id = Column(Integer, primary_key = True)
 text = Column(Text)
 condition = Column(Text)
 action = Column(Text)

 next_lines = relationship(Association, backref="prev_lines")



class Root(Base):
 __tablename__ = 'root'

 name = Column(String, primary_key = True)
 start_line_id = Column(Integer, ForeignKey('line.id'))

 start_line = relationship('Line')

But I get the following error: sqlalchemy.exc.ArgumentError: Could not determine join condition between parent/ child tables on relationship Line.next_lines. Specify a 'primaryjoin' expressio n. If 'secondary' is present, 'secondaryjoin' is needed as well.

Do you know how I could remedy this?


回答1:


You should just need:

prev_lines = relationship(
    Association,
    backref="next_lines",
    primaryjoin=id==Association.prev_id)

Since this specifies the next_lines back reference there is no need to have a next_lines relationship.

You can also do this using the remote_side parameter to a relationship: http://www.sqlalchemy.org/trac/browser/examples/adjacency_list/adjacency_list.py



来源:https://stackoverflow.com/questions/4177235/many-to-many-self-referential-relationship-in-sqlalchemy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!