13

我试图在 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”。

你知道我该如何补救吗?

4

1 回答 1

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

于 2010-11-17T15:06:05.770 回答