SQLAlchemy 连接来自同一个表的多个列
Posted
技术标签:
【中文标题】SQLAlchemy 连接来自同一个表的多个列【英文标题】:SQL Alchemy Join Multiple Columns from same table 【发布时间】:2016-02-10 23:01:08 【问题描述】: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')
我需要编写一个查询来连接列和团队表,以显示本地和客队的团队信息。
Session.query(Match.date, Match.home_team.name, Match_away_team.name).joins(Team)
这会返回Can't determine join between 'matches' and 'teams'; tables have more than one foreign key constraint relationship between them. Please specify the 'onclause' of this join explicitly
【问题讨论】:
【参考方案1】:首先,您的代码不起作用的原因是因为 SQLAlchemy 不知道您是想通过home_team
还是away_team
加入Team
,所以您必须告诉它。此外,您还需要加入Team
两次,这使事情变得更加复杂。
使用joinedload
可以更轻松地完成此操作:
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
m.home_team
和 m.away_team
将使用 JOIN
在与 m
相同的查询中加载。
如果您坚持使用显式 .join()
,则必须使用 alias 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
【讨论】:
这是如何使用它的完美说明。我测试了你后面的例子,效果很好。以上是关于SQLAlchemy 连接来自同一个表的多个列的主要内容,如果未能解决你的问题,请参考以下文章
SQLAlchemy filter_by 来自同一列的多个项目