我知道关于同一主题存在许多问题,但我在某一点上感到困惑。我的意图是在表单上显示两个 ModelChoiceField,但不直接将它们绑定到 Game 模型。
我有以下内容:
表格.py
class AddGame(forms.ModelForm):
won_lag = forms.ChoiceField(choices=[('1','Home') , ('2', 'Away') ])
home_team = forms.ModelChoiceField(queryset=Player.objects.all())
away_team = forms.ModelChoiceField(queryset=Player.objects.all())
class Meta:
model = Game
fields = ('match', 'match_sequence')
视图.py
def game_add(request, match_id):
game = Game()
try:
match = Match.objects.get(id=match_id)
except Match.DoesNotExist:
# we have no object! do something
pass
game.match = match
# get form
form = AddGame(request.POST or None, instance=game)
form.fields['home_team'].queryset = Player.objects.filter(team=match.home_team )
# handle post-back (new or existing; on success nav to game list)
if request.method == 'POST':
if form.is_valid():
form.save()
# redirect to list of games for the specified match
return HttpResponseRedirect(reverse('nine.views.list_games'))
...
我感到困惑的是在设置查询集过滤器时。首先我试过:
form.home_team.queryset = Player.objects.filter(team=match.home_team )
但我收到了这个错误
AttributeError at /nine/games/new/1
'AddGame' object has no attribute 'home_team'
...
所以我将其更改为以下内容:(阅读其他帖子后)
form.fields['home_team'].queryset = Player.objects.filter(team=match.home_team )
现在它工作正常。
所以我的问题是,这两条线有什么区别?为什么第二个有效而不是第一个?我确信这是一个新手(我是一个)问题,但我很困惑。
任何帮助,将不胜感激。