Python SQL Alchemy将同一表中的多个列连接起来
我需要编写一个查询,连接列和团队表,显示本地团队和客场团队的团队信息Python SQL Alchemy将同一表中的多个列连接起来,python,sql,join,sqlalchemy,Python,Sql,Join,Sqlalchemy,我需要编写一个查询,连接列和团队表,显示本地团队和客场团队的团队信息 class Match(Base): __tablename__ = 'matches' id = Column(Integer, primary_key=True) date = Column(Date, nullable=False) time = Column(Time, nullable=True) league_id = Column(ForeignKey('leagues.
class Match(Base):
__tablename__ = 'matches'
id = Column(Integer, primary_key=True)
date = Column(Date, nullable=False)
time = Column(Time, nullable=True)
league_id = Column(ForeignKey('leagues.id'), nullable=False, index=True)
league = relationship('League', backref='matches')
type = Column(enums.matches_types)
home_team_id = Column(ForeignKey('teams.id'), nullable=False, index=True)
home_team = relationship('Team', foreign_keys=[home_team_id], backref='home_matches')
away_team_id = Column(ForeignKey('teams.id'), nullable=False, index=True)
class Team(Base):
__tablename__ = 'teams'
id = Column(Integer, primary_key=True)
name = Column(String, nullable=False)
country_id = Column(ForeignKey('countries.id'), nullable=False, index=True)
country = relationship('Country', backref='teams')
这返回
无法确定“匹配”和“团队”之间的连接;表之间有多个外键约束关系。请明确指定此加入的“onclause”
首先,您的代码不起作用的原因是因为SQLAlchemy不知道您是想通过主队
还是客队
加入团队,所以您必须告诉它。此外,您还需要两次加入团队
,这会使事情更加复杂
这可以通过以下方式更轻松地完成:
m.home\u团队
和m.away\u团队
将使用JOIN
在与m
相同的查询中加载
如果您坚持使用显式的.join()
,您将不得不使用团队
实体(未测试):
这是如何使用它的完美例证。我测试了您后面的示例,效果很好。
Session.query(Match.date, Match.home_team.name, Match_away_team.name).joins(Team)
matches = session.query(Match).options(joinedload(Match.home_team),
joinedload(Match.away_team))
for m in matches:
print m.date, m.home_team, m.away_team
home = aliased(Team)
away = aliased(Team)
q = session.query(Match.date, home, away).join(home, Match.home_team) \
.join(away, Match.away_team)
for date, home_team, away_team in q:
print date, home_team, away_team