保存其他表单时如何更新其他模型字段

时间:2019-10-05 04:09:05

标签: django django-models django-templates

嗨,我有2个模型GameMatch

models.py

class Game(models.Model):
    title = models.CharField(max_length=255)
    team1score = models.IntegerField(null=True, blank=True,default=0)
    ...
    team2score = models.IntegerField(null=True, blank=True,default=0)
    ...



class Match(models.Model):
    title = models.CharField(max_length=255)
    game=models.ForeignKey(Game,on_delete=models.CASCADE)
    team1score = models.IntegerField(null=True, blank=True,default=0)
    ...
    team2score = models.IntegerField(null=True, blank=True,default=0)
    ...

forms.py

class MatchForm(forms.ModelForm):
    team1score = forms.IntegerField(widget=forms.TextInput,required=False)
    team2score = forms.IntegerField(widget=forms.TextInput,required=False)


    class Meta:
        model=Match
        fields=['team1score',
                'team2score',
                ...
                ]

我正在使用以下代码创建一个匹配对象。

views.py

def creatematch(request,...):
     form = MatchForm(request.POST or None)

        if form.is_valid():
            match = form.save(commit=False)
            ...

            match.save()
            ...

现在,我的问题是如何更新game.team1scoregame.team2score 当我创建match对象

1 个答案:

答案 0 :(得分:0)

使用您的ForeignKey模型的Match关系来获取所需的Game实例:

def creatematch(request,...):
     form = MatchForm(request.POST or None)

        if form.is_valid():
            match = form.save(commit=False)[0]
            game = match.game 
            game.team1score += match.team1score
            game.team2score += match.team2score
            game.save()
            match.save()

但这是次优的解决方案,因为您实际上运行了SELECT * FROM GAME,等待结果,然后执行计算,然后再向数据库发送第二个查询。

您应该使用F(),它会在您的数据库中执行以下计算:

from django.db.models import F

def creatematch(request,...):
     form = MatchForm(request.POST or None)

        if form.is_valid():
            match = form.save(commit=False)[0]
            game = match.game 
            game.team1score = F('team1score') + match.team1score
            game.team2score = F('team2score') + match.team2score

            game.save()
            match.save()