【问题标题】:SQLALchemy - populate relationship with rows from 2 fields in another tableSQLALchemy - 使用另一个表中 2 个字段的行填充关系
【发布时间】:2020-02-03 21:36:15
【问题描述】:

我有以下表格:

class Match(Base):
    __tablename__ = 'match'

    match_id = Column(Integer, primary_key=True)
    home_team_id = Column(Integer, ForeignKey('team.team_id'))
    away_team_id = Column(Integer, ForeignKey('team.team_id'))

    home_team = relationship('Team', foreign_keys=[home_team_id])
    away_team = relationship('Team', foreign_keys=[away_team_id])

class Team(Base):
    __tablename__ = 'team'

    team_id = Column(Integer, primary_key=True)
    name = Column(String)

    matches = relationship(...)

如果团队的team_id 匹配home_team_idaway_team_id,我将如何定义Team 中的关系,以便team.matches 将从match 表中提取每一行?

谢谢。

【问题讨论】:

    标签: python database sqlite sqlalchemy


    【解决方案1】:

    好的,我想通了。需要的关系是:

    matches = relationship(
        'Match', 
        primaryjoin='or_(
            Team.team_id == Match.home_team_id, Team.team_id == Match.away_team_id
        )'
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-12
      • 1970-01-01
      相关资源
      最近更新 更多