django - queryset diference - 不按我的预期工作

时间:2013-08-01 02:54:19

标签: django django-queryset

我害怕另一个新手问题。我有3个列表的这个表格。目标是更改2个列表的查询集(请参阅视图中的代码)

form.py

class AddGameForm(forms.ModelForm):
    won_lag = forms.ChoiceField(choices=[('1','Home') , ('2', 'Away') ], )
    home_team = forms.ModelChoiceField(queryset=Player.objects.all(),required=True )
    away_team = forms.ModelChoiceField(queryset=Player.objects.all(), required=True )

    class Meta:
        model = Game
        fields = ()

view.py

def game_add(request, match_id):
    # used to create a new Game

    """ return http response page for creating a new Game """

    # Adding a new Game so just make a new one
    game = Game()

    # Get the match specified in the Querystring because we will need it to figure out     who the home team
    # and away team are.
    try:
        match = Match.objects.get(id=match_id)
    except Match.DoesNotExist:
        # we have no object!  do something
        #todo: redirect to list match page?
    pass

    # get form
    form = AddGameForm(request.POST or None, instance=game)

    # Change the Queryset for Home and Away team to show only players that are on the team
    #  AND have not already played in a game so we need to get the "DIFFERENCE" between all
    #  team members and any players that have already played in the match
    home_players = Player.objects.filter(team=match.home_team)            # All Home Team members
    away_players = Player.objects.filter(team=match.away_team)            # All Away Team members
    already_played_in_match_players = Game.objects.filter(match=match)    # This is both home and away players
                                                                      # that have played in a Game on this match

    form.fields['home_team'].queryset = home_players.exclude(pk__in=already_played_in_match_players)
    form.fields['away_team'].queryset = away_players.exclude(pk__in=already_played_in_match_players)
...

在我的数据库中,我有以下内容:

Team 1
   Player 1
   Player 2
Team 2
   Player 3

Match 1
   no games

因此,当我按预期打开表单时,home_team列表显示Player1,Player2和away_team列表显示Player3

所以我选择了Player 1和Player3,然后保存游戏。 现在DB有以下数据

Team 1
   Player 1
   Player 2
Team 2
   Player 3

Match 1
   Game 1 between Player1 and Player3

我决定添加另一个游戏,所以我打开GameAddForm并期望home_team列表只显示Player2和away_team列表以显示没有玩家。

然而,实际上,发生的情况是home_team列表按预期运行, away_team列表仍显示播放器3.

我完全感到困惑的是为什么它适用于主队而不是客队。

有什么建议吗?

提前感谢您提供的任何指导。

1 个答案:

答案 0 :(得分:0)

好吧,想通了。基本上问题出在以下几行:

already_played_in_match_players = Game.objects.filter(match=match)

返回游戏的查询集,而不是玩家

由于我想获得玩家,我必须从Player.object开始。这意味着我不得不向后查询游戏→Player1和Game→Player2关系。以下是文档对此的说法:

Lookups that span relationships

To span a relationship, just use the field name of related fields across models, separated by double underscores, until you get to the field you want

...

To refer to a “reverse” relationship, just use the lowercase name of the model.
为了清楚起见,我把它分成了几个步骤。

inner_query = Game.objects.filter(match=match)  # Gets all games in this match

然后我使用了以下内容:

Player.objects.filter(player1__in=inner_query)  

基本上说,获取内部查询集中任何Game对象中player1 foreignkey引用的所有Player对象。

接下来我使用了| (管道)到UNION一个player1和player2的查询集 所以它导致了这一行:

already_played_players = Player.objects.filter(player1__in=inner_query) | Player.objects.filter(player2__in=inner_query)

这给了我一个已经参加过比赛的所有球员名单的预期效果。

变更摘要

我将违规行更改为以下内容:

...

inner_query = Game.objects.filter(match=match)    # All games in this match

# Now use reverse relation to get the Player1 union Player2 to get all players who have played in this match so far
already_played_players = Player.objects.filter(player1__in=inner_query) | Player.objects.filter(player2__in=inner_query)

...