2014-07-27 34 views
4

多個外鍵關係,我有以下Peewee PostgreSQL的模型:保存Peewee查詢與對同桌

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') 

你可以看到,該模型有一個團隊模型中的兩個外鍵關係。

我想要做的事,如:

不幸的是,雖然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 

回答

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