【发布时间】:2021-11-29 01:00:29
【问题描述】:
我的数据库中有两张表,一张用于比赛,一张用于团队。比赛的列中存储了参赛球队的 ID。
class Match(Base):
id_ = Column(UUID(as_uuid=True, primary_key=True)
team1_id = Column(UUID(as_uuid=True), ForeignKey('teams.id')
team2_id = Column(UUID(as_uuid=True), ForeignKey('teams.id')
class Team(Base):
id_ = Column(UUID(as_uuid=True, primary_key=True)
我想在两个表之间创建这样的关系:
Match.teams返回两个Team对象的列表,其中包含 id 与team1_id或team2_id匹配的团队Team.matches返回Match对象列表,其中包含team1_id或team2_id列中存在该团队ID 的所有匹配项
从 SQL 的角度来看,我不需要另一个表 - 所有关系信息都存在于上述表中。但是,SQLAlchemy 是否需要关联表才能工作?
尝试 1:
class Match(Base):
...
teams = relationship('Team', back_populates='matches', lazy='selectin',
foreign_keys=[team1_id, team2_id])
class Team(Base):
...
matches = relationship('Match', back_populates='teams', lazy='selectin')
导致以下错误:
sqlalchemy.exc.AmbiguousForeignKeysError: Could not determine join condition between parent/child tables on relationship Match.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.
这让我感到困惑,因为我认为那是我正在做的事情!我做错了什么?
尝试 2:
class Match(Base):
...
teams = relationship('Team',
back_populates='matches',
lazy='selectin',
primaryjoin=('or_(Team.id==Match.team1_id,'
'Team.id==Match.team2_id)'))
class Team(Base):
...
matches = relationship('Match', back_populates='teams', lazy='selectin')
这导致 Match.teams 返回第一个团队的单个值,其 id 与 team1_id 或 team2_id 匹配。
我想做的事可能吗?应该怎么做?是否可以不在数据库中创建另一个表?
【问题讨论】:
标签: python sqlalchemy relationship