SQLAlchemy中的多对多自引用关系

14

我正在尝试在SQLAlchemy中创建一个自引用的多对多关系(这意味着Line可以有许多父行和许多子行),代码如下:

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')

但我得到了以下错误: sqlalchemy.exc.ArgumentError: 无法在关系Line.next_lines上确定父/子表之间的连接条件。请指定“primaryjoin”表达式。如果存在“secondary”,则还需要“secondaryjoin”。

你知道我该如何解决这个问题吗?


我尝试了这个: next_lines = relationship(Association, backref="prev_lines", primaryjoin=id==Association.next_id) prev_lines = relationship(Association, backref="next_lines", primaryjoin=id==Association.prev_id) 现在它没有产生任何错误。这是正确的解决方案吗?还是会产生其他问题? - mike
1个回答

7

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接