在SQLAlchemy文档中,有一个关于多对多关系的好例子。请参阅第二个代码块: http://docs.sqlalchemy.org/en/latest/orm/basic_relationships.html#many-to-many
我想做同样的事情,但是使用单个数据表,以便对象的父(s)和子(ren)属于同一类型。
我尝试的是这样的:
association_table = Table('association', Base.metadata,
Column('left_id', Integer, ForeignKey('mytable.id')),
Column('right_id', Integer, ForeignKey('mytable.id'))
)
class MyTable(Base):
__tablename__ = 'mytable'
id = Column(Integer, primary_key=True)
children = relationship(
"MyTable",
secondary=association_table,
back_populates="parents")
parents = relationship(
"MyTable",
secondary=association_table,
back_populates="children")
不幸的是,这会产生错误消息:
sqlalchemy.exc.AmbiguousForeignKeysError: Could not determine join condition between parent/child tables on relationship MyTable.children - there are multiple foreign key paths linking the tables via secondary table 'association'. Specify the 'foreign_keys' argument, providing a list of those columns which should be counted as containing a foreign key reference from the secondary table to each of the parent and child tables.
我确实理解错误及其发生的原因,但我无法弄清楚,如何在SQLAlchemy中解决它。有人可以帮忙吗?感谢。
干杯, 添