更新时间:2022-12-12 15:25:19
首先,您的代码不起作用的原因是因为SQLAlchemy不知道您是否要通过home_team
或Team
,这会使事情变得更加复杂.
First, the reason your code doesn't work is because SQLAlchemy doesn't know whether you want to join to Team
via home_team
or away_team
, so you'll have to tell it. In addition, you'll need to join to Team
twice, which further complicates things.
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
相同的查询中加载.
m.home_team
and m.away_team
will be loaded in the same query as m
using a JOIN
.
如果您坚持使用显式的.join()
,则必须别名 Team
实体(未测试):
If you insist on using an explicit .join()
you'll have to alias the Team
entities (not tested):
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