首页 > 解决方案 > 具有多个外键的 SQLAlchemy 辅助表

问题描述

我正在尝试使用 Flask 和 SQLAlchemy 制作类似于社交网络的东西。

我做了一个人模型

class Person(SqlAlchemyBase, UserMixin, SerializerMixin):
    __tablename__ = 'persons'

    id = Cl(sql.Integer, primary_key=True, autoincrement=True)
    # some fields
    friends = orm.relation('Person', secondary='friendships')

和友谊模型

class Friendship(SqlAlchemyBase):
    __tablename__ = 'friendships'
    id = Cl(sql.Integer, primary_key=True, autoincrement=True)
    person1_id = Cl(sql.Integer, sql.ForeignKey('persons.id', ondelete='CASCADE'))
    person2_id = Cl(sql.Integer, sql.ForeignKey('persons.id', ondelete='CASCADE'))

它引发了这个异常:

sqlalchemy.exc.AmbiguousForeignKeysError: Could not determine join condition between parent/child tables on relationship Person.friends - there are multiple foreign key paths linking the tables via secondary table 'friendships'.  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.

我怎么解决这个问题?

标签: pythonsqlalchemy

解决方案


所以,我解决了这个问题。我应该做的就是添加primaryjoin和secondaryjoin:

class Person(SqlAlchemyBase, UserMixin, SerializerMixin):
    __tablename__ = 'persons'

    id = Cl(sql.Integer, primary_key=True, autoincrement=True)
    # some fields
    friends = orm.relation('Person', secondary='friendships', secondaryjoin=Friendship.person1_id==id, primaryjoin=Friendshup.person2_id==id)

这确实有效!


推荐阅读