如何显示投票的总票数?



我有一个简单的投票程序。

models:

class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
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=200)
votes = models.IntegerField(default=0)
def __str__(self):
return self.choice_text

results.html:

{% extends 'base.html' %}
{% block content %}
<h1 class="mb-5 text-center">{{ question.question_text }}</h1>
<ul class="list-group mb-5">
{% for choice in question.choice_set.all %}
<li class="list-group-item">
{{ choice.choice_text }}  <span class="badge badge-success float-right">{{ choice.votes }} vote{{ choice.votes | pluralize }}</span>
</li>
{% endfor %}
</ul>
<a class="btn btn-secondary" href="{% url 'polls:index' %}">Back To Polls</a>
<a class="btn btn-dark" href="{% url 'polls:detail' question.id %}">Vote again?</a>
{% endblock %}

views.py:

def vote(request, question_id):
question = get_object_or_404(Question, pk=question_id)
try:
selected_choice = question.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
return render(request, 'polls/detail.html', {
'question': question,
'error_message': "You didn't select a choice.",
})
else:
selected_choice.votes += 1
selected_choice.save()
return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))

如何为每个question制作total的投票数,以便您可以在底部显示total:和本次投票的总投票数。

在这些情况下,我通常会做的是在Question模型上添加一个名为total_votes的属性,该属性计算每个选择的总票数。你也可以利用Django ORM中的一些聚合函数。

class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __str__(self):
return self.question_text
@property
def total_votes(self):
return self.choice_set.aggregate(Sum('votes'))['votes__sum']

然后你可以像使用模型实例的实际属性一样使用total_votes属性。警告:不可能在查询集(过滤等)中使用。

显示:

{% extends 'base.html' %}
{% block content %}
<h1 class="mb-5 text-center">{{ question.question_text }}</h1>
<h2 class="mb-5 text-center">Total votes: {{ question.total_votes }}</h2>
<ul class="list-group mb-5">
{% for choice in question.choice_set.all %}
<li class="list-group-item">
{{ choice.choice_text }}  <span class="badge badge-success float-right">{{ choice.votes }} vote{{ choice.votes | pluralize }}</span>
</li>
{% endfor %}
</ul>
<a class="btn btn-secondary" href="{% url 'polls:index' %}">Back To Polls</a>
<a class="btn btn-dark" href="{% url 'polls:detail' question.id %}">Vote again?</a>
{% endblock %}

相关内容

  • 没有找到相关文章

最新更新