SQLAlchemy ошибка отношения многих ко многим - PullRequest
0 голосов
/ 19 апреля 2020

Я придерживаюсь отношений «многие ко многим», описанных на: https://docs.sqlalchemy.org/en/14/orm/basic_relationships.html#many-ко-многим

И я цитирую код с сайта:

association_table = Table('association', Base.metadata,
    Column('left_id', Integer, ForeignKey('left.id')),
    Column('right_id', Integer, ForeignKey('right.id'))
)

class Parent(Base):
    __tablename__ = 'left'
    id = Column(Integer, primary_key=True)
    children = relationship(
        "Child",
        secondary=association_table,
        back_populates="parents")

class Child(Base):
    __tablename__ = 'right'
    id = Column(Integer, primary_key=True)
    parents = relationship(
        "Parent",
        secondary=association_table,
        back_populates="children")

Появляется эта ошибка:

sqlalchemy.exc.NoForeignKeysError: Could not determine join condition between parent/child tables on relationship User.followings - there are no foreign keys linking these tables.  Ensure that referencing columns are associated with a ForeignKey or ForeignKeyConstraint, or specify a 'primaryjoin' expression.

Я также пытаюсь добавить, как primaryjoin и secondjoin (этот фрагмент кода взят из https://docs.sqlalchemy.org/en/14/orm/join_conditions.html):

node_to_node = Table("node_to_node", Base.metadata,
    Column("left_node_id", Integer, ForeignKey("node.id"), primary_key=True),
    Column("right_node_id", Integer, ForeignKey("node.id"), primary_key=True)
)

class Node(Base):
    __tablename__ = 'node'
    id = Column(Integer, primary_key=True)
    label = Column(String(length=20))
    right_nodes = relationship("Node",
                        secondary=node_to_node,
                        primaryjoin=id==node_to_node.c.left_node_id,
                        secondaryjoin=id==node_to_node.c.right_node_id,
                        backref="left_nodes"
    )

Появляется с теми же ошибками. Мне интересно знать, где моя ошибка, и я буду очень признателен, если вы мне это скажете!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...