我想连接两个型号。
模型#1称为“组”。它通过starter_id,main_id,dessert_id连接到几个“团队”。我希望有一个名为“团队”的字段,其中包含所有已连接团队的列表。
class Group(db.Model):
__tablename__ = 'groups'
id = db.Column(db.Integer, primary_key=True)
starter_id = db.Column(db.Integer, db.ForeignKey('teams.id'))
main_id = db.Column(db.Integer, db.ForeignKey('teams.id'))
dessert_id = db.Column(db.Integer, db.ForeignKey('teams.id'))
#Relationships
teams = db.relationship('Team', back_populates="group", foreign_keys= \
[starter_1_id, starter_2_id, starter_3_id, main_1_id, main_2_id, main_3_id, \
dessert_1_id, dessert_2_id, dessert_3_id])
class Team(db.Model):
__tablename__ = 'teams'
id = db.Column(db.Integer, primary_key=True)
group_id = db.Column(db.Integer, db.ForeignKey('groups.id'))
# Relationships
group = db.relationship("Group", back_populates="teams", foreign_keys=[group_id])
我收到此错误:
sqlalchemy.exc.AmbiguousForeignKeysError: Could not determine join condition
between parent/child tables on relationship Group.teams - there are multiple
foreign key paths linking the tables. Specify the 'foreign_keys' argument,
providing a list of those columns which should be counted as containing a
foreign key reference to the parent table.
我显然不知道如何修复该错误;)
答案 0 :(得分:0)
一个团队属于一个团队"关系(Team.group
)及其逆,"一个团队有很多团队" (Group.teams
)由外键Team.group_id
给出,因此您需要写:
teams = db.relationship('Team', back_populates="group", foreign_keys=lambda: Team.group_id)