我有以下Peewee PostgreSQL模型:
class Game(Model):
class Meta:
database = db
db_table = 'd_games'
game_id = PrimaryKeyField()
location = CharField()
home_team = ForeignKeyField(Team, related_name='home_games')
away_team = ForeignKeyField(Team, related_name='away_games')
您可以看到该模型与Team模型有两个外键关系。
我想做类似的事情:
games = Game.select(Game, Team).join(Team).limit(10)
for g in games:
print '%s vs. %s' % (g.home_team.team_name, g.away_team.team_name)
不幸的是,home_team
关系会在初始查询中保存:
# from the query log
'SELECT t1."game_id", t1."game_date", t1."location", t1."home_team_id", t1."away_team_id", t2."team_id", t2."team_name"
FROM "d_games" AS t1
INNER JOIN "d_team" AS t2
ON (t1."home_team_id" = t2."team_id")
LIMIT 10
away_team
关系没有,因此每次我尝试打印g.away_team.team_name
时都会执行新查询。
如何解决此问题,以便home_team
和away_team
关系得到保存?我试过了
games = Game.select(Game, Team, Team).join(Team).switch(Game).join(Team).limit(10)
但这会给我一个table name "t2" specified more than once
错误,因为Peewee试图执行的查询是
'SELECT t1."game_id", t1."game_date", t1."location", t1."home_team_id", t1."away_team_id", t2."team_id", t2."team_name", t2."team_id", t2."team_name"
FROM "d_games" AS t1
INNER JOIN "d_team" AS t2
ON (t1."home_team_id" = t2."team_id")
INNER JOIN "d_team" AS t2
ON (t1."home_team_id" = t2."team_id")
LIMIT 10
答案 0 :(得分:4)
在这些情况下,您需要使用Model.alias()
。这是一个例子:
HomeTeam = Team.alias()
AwayTeam = Team.alias()
query = (Game
.select(Game, HomeTeam, AwayTeam)
.join(HomeTeam, on=(Game.home_team == HomeTeam.id))
.switch(Game)
.join(AwayTeam, on=(Game.away_team == AwayTeam.id))
.order_by(Game.id))
结果是
SELECT
t1."id", t1."location", t1."home_team_id", t1."away_team_id",
t2."id", t2."name",
t3."id", t3."name"
FROM "d_games" AS t1
INNER JOIN "team" AS t2 ON (t1."home_team_id" = t2."id")
INNER JOIN "team" AS t3 ON (t1."away_team_id" = t3."id")
ORDER BY t1."id
然后:
for game in query:
print game.home_team.name, game.away_team.name