我有一份民意测验清单(问题),想检查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()
...
我ManyToMany
在Question
模型中添加了一个字段,在阅读文档后,我认为这是链接对某个问题进行投票的用户列表的正确方法,但是我不确定。最终目标是在我的模板中添加以下内容:if request.user in question.has_answered: don't display the poll
我将如何处理?
首先,需要解决一些逻辑和示意图问题。
您正在根据question_text
可能返回多个对象的非唯一字段过滤问题。您应该通过以下方式检索问题id
:
q = Question.objects.get(pk=question)
或使question_text
字段唯一:
question_text = models.CharField(max_length=80, unique=True)
其次,votes
通过Python加1可能会导致比赛条件,这可能发生在两个用户想要同时增加选票的情况下。这就是为什么F
Django中存在可以让您在数据库级别进行增量操作的对象的原因:
from django.db.models import F
def poll_answer(request):
...
choice = Choice.objects.get(id=answer)
choice.votes = F("votes") + 1
choice.save()
...
我有一个民意测验(问题)列表,并想检查某个用户是否对该民意测验进行了投票。
按照您的设计,您不能这样做,因为您没有存储谁投票给哪个问题。votes
当用户对问题投票时,您只是在增加字段。
一种方法是,您可以将votes
字段更改为ManyToManyField
并开始存储对选项进行投票的用户:
class Question(models.Model):
text = models.CharField(max_length=80, unique=True)
def __str__(self):
return self.text
class Choice(models.Model):
question = models.ForeignKey(Question)
choice = models.CharField(max_length=100)
votes = models.ManyToMany(User)
因此您可以按照以下步骤检查用户是否对投票进行了投票:
has_voted = request.user.choice_set.filter(question=question).exists()
此外,在我看来,这里的投票动作可以充当和模型之间的中间模型Question
,User
因此您可能想看看如何在Django文档的“多对多关系”部分中定义额外的字段。
如果我穿上你的鞋子,我会做以下事情:
class Question(models.Model):
text = models.CharField(max_length=80, unique=True)
voters = models.ManyToManyField(User, through="Vote")
class Choice(models.Model):
question = models.ForeignKey(Question)
text = models.CharField(max_length=100)
class Vote(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE)
choice = models.ForeignKey(Choice, on_delete=models.CASCADE)
voted_at = models.DateTimeField(auto_now_add=True)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句