如何建立自引用的多对多关系

时间:2021-03-08 03:07:23

标签: python sqlalchemy many-to-many

我有一个名为 people 的表,我想建立一种方法来跟踪不同人之间的关系。我认为最好的方法是使用人与人之间的中间表建立多对多关系。

relationships = Table('relationships', Base.metadata,
    Column('person_one', ForeignKey('person.id')),
    Column('person_two', ForeignKey('person.id'))

class Person(Base):
    """table to store information about a person
    most information is going to be saved as a fact tied to this table"""
    __tablename__ = 'people'

    id                  = Column(Integer, primary_key=True)
    source_id           = Column(Integer, ForeignKey('sources.id'))

    # one to many relationships
    facts               = relationship("Fact", back_populates="person")
    source              = relationship("Source", back_populates="people")

    # many:many
    children = relationship("Person", secondary=relationships, back_populates="parents")
    parents = relationship("Person", secondary=relationships, back_populates="children")

    def __repr__(self):
        return f"<People(id='{self.id}', source_id='{self.source_id}')>"

我收到以下错误:

sqlalchemy.exc.NoForeignKeysError: Could not determine join condition
between parent/child tables on relationship Person.children - there are 
no foreign keys linking these tables via secondary table 'relationships'.  
Ensure that referencing columns are associated with a ForeignKey or 
ForeignKeyConstraint, or specify 'primaryjoin' and 'secondaryjoin' expressions.

0 个答案:

没有答案
相关问题