【问题标题】:Prevent duplicate voting when there's more than one possible selection?当有多个可能的选择时防止重复投票?
【发布时间】:2017-08-29 19:49:49
【问题描述】:

我正在尝试使用 Django 设置一个投票系统,该系统限制注册用户在一次投票中只能投票一次(尽管有多个选项可用,同意/强烈同意/不同意)。到目前为止,我已经能够建立一个系统,他们不能做出完全相同的投票(所以他们不能两次投票“同意”),但他们可以改变他们的投票并且仍然通过(所以他们可以投“同意”,然后再次投“不同意”)。我希望每个主题只能投一票,而且我不知道如何调整我的代码来实现这一点。这是我的看法:

def vote(request, prediction_id):
    prediction = get_object_or_404(Prediction, pk=prediction_id)
    selected_choice = prediction.choice_set.get(pk=request.POST['choice'])

    if Voter.objects.filter(prediction=prediction, choice=selected_choice, user_id=request.user.id).exists():

        return render(request, 'predictions/detail.html', {
            'prediction': prediction,
            'error_message': "Sorry, but you have already voted."
        })

    else:

        selected_choice.votes += 1
        selected_choice.save()
        Voter.objects.create(prediction=prediction, choice=selected_choice, user_id=request.user.id)

    return HttpResponseRedirect(reverse('predictions:results', args=(prediction.id,)))

这是我的模型:

class Prediction(models.Model):
    prediction_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')
    # ...
    def __str__(self):
        return self.prediction_text

class Choice(models.Model):
    prediction = models.ForeignKey(Prediction, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)
    def __str__(self):
        return self.choice_text

class Voter(models.Model):
    user = models.ForeignKey(User)
    choice = models.ForeignKey(Choice)
    prediction = models.ForeignKey(Prediction)

【问题讨论】:

  • 您可能希望重新设计您的模型以拥有Topic 模型、“Choice”模型和“VoterChoice”模型,其中“VoterChoice”具有属性topicuser、@ 987654326@ 和 (topic, user) 上的唯一约束。
  • 我将如何将唯一约束放在那里?我相信您提到的主题/用户/选择模型等价于我的预测/选择/投票者模型,它们只是名称不同。我认为,我真正苦苦挣扎的唯一部分是通过设置独特的约束来限制投票者。

标签: python django sqlite


【解决方案1】:
if Voter.objects.filter(prediction=prediction, user_id=request.user.id).exists()

此行代码说明此用户是否对任何选项进行了投票。

如果我能理解的话,Prediction 类就是“问题”。所以其他解决方案是:

class Voter(models.Model):
    user = models.ForeignKey(User)
    choice = models.ForeignKey(Choice)
    prediction = models.ForeignKey(Prediction)

Meta:
    unique_together = (("driver", "prediction"),)

【讨论】:

    猜你喜欢
    • 2013-05-27
    • 1970-01-01
    • 1970-01-01
    • 2012-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多