繁体   English   中英

使用针对同一表的多个外键关系保存Peewee查询

[英]Saving Peewee queries with multiple foreign key relationships against the same table

我有以下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_teamaway_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

在这些情况下,您需要使用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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM