Django M2M字段删除方法不起作用

时间:2018-08-31 15:36:21

标签: django django-models django-forms

我有一个模特:

class Vote(models.Model):
    text = models.CharField(max_length=300)
    voters = models.ManyToManyField(CustomUser, blank=True, related_name="voters")
    voters_voted = models.ManyToManyField(CustomUser, blank=True, related_name="voted")
    game = models.ForeignKey(Game, on_delete=models.CASCADE)
    in_favour = models.PositiveIntegerField(default=0)
    against = models.PositiveIntegerField(default=0)

    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)
        queryset = self.game.players
        for player in queryset:
            self.voters.add(player)

还有一个投票表,具有以下form_valid方法:

def form_valid(self, form):
        game = Game.objects.get(id=foo)
        vote = Vote.objects.get(id=bar)
        if form.cleaned_data['choice'] == 'Y':
            vote.in_favour += 1
        else form.cleaned_data['choice'] == 'N':
            vote.against += 1

        vote.voters.remove(self.request.user) #This line doesn't work
        vote.voters_voted.add(self.request.user)
        vote.save()
        return super().form_valid(form)

这样做的目的是跟踪哪些用户已投票,哪些人有资格投票以及投票是什么(赞成/反对)。

此代码中的所有内容都可以正常运行,但该行可以在用户提交表单(vote.voters.remove(self.request.user)时将他们从投票者组中删除。以下将用户添加到投票组(vote.voters_voted.add(self.request.user))的行效果很好。

我尝试在这两行之间插入第二个vote.save(),但这没有任何区别。我不明白为什么第二行有效,但是第一行无效!

1 个答案:

答案 0 :(得分:0)

在删除user之前保存对象。

解决方案

vote.save() # call this first, because it adds the game players which could include the user you are removing
vote.voters.remove(self.request.user)