sqlalchemy中的多对多自我指涉关系

时间:2010-11-14 11:23:28

标签: many-to-many sqlalchemy relationship self-reference

我正试图在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'expressio ñ。如果存在'secondary',则还需要'secondaryjoin'。

你知道我怎么能解决这个问题吗?

1 个答案:

答案 0 :(得分:7)

你应该只需要:

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

由于这指定了next_lines后退引用,因此不需要next_lines关系。

您也可以使用关联的remote_side参数执行此操作:http://www.sqlalchemy.org/trac/browser/examples/adjacency_list/adjacency_list.py