我有民意調查清單(問題),並希望檢查某個User
是否對該民意調查投了票。這裏是我的模型:檢查用戶是否對某項民意調查投了票
class Question(models.Model):
has_answered = models.ManyToManyField(User)
question_text = models.CharField(max_length=80)
def __str__(self):
return self.question_text
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=100)
votes = models.IntegerField(default=0)
def __str__(self):
return self.choice_text
這是我的看法,當投票表決用戶投票:
def poll_answer(request):
if request.method == 'POST':
answer = request.POST.get('answer')
question = request.POST.get('question')
q = Question.objects.get(question_text=question)
choice = Choice.objects.get(id=answer)
choice.votes += 1
choice.save()
...
我已經在我的Question
模式,閱讀文檔後,我認爲這是增加了一個ManyToMany
場正確的方式來鏈接在某個問題上投票的用戶名單,但我不確定是否誠實。最終目標是放入我的模板,如下所示:if request.user in question.has_answered: don't display the poll
我該如何去做這件事?