python - 具有多个外键的 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.
我怎么解决这个问题?
解决方案
所以,我解决了这个问题。我应该做的就是添加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)
这确实有效!
推荐阅读
- java - Micronaut cli graphql 设置
- c# - 如何获取字符串内部数据类型的大小?
- fortran - 为什么当我更改结果变量的名称时,使用 f2py 编译的 Fortran 函数返回零?
- dictionary - 使用静态映射的类无法编译
- angular - URLSearchParams 不是构造函数
- javascript - 在 VUE 中拖放文件
- scala - Scala 类型检查抱怨 lambda,而不是显式 Function
- javascript - Why does the youtube ytplayer object not update when navigating between youtube videos?
- typescript - 打字稿找不到自定义类型定义文件
- git - 为什么git是法语的?