如何显示投票中的总票数?

How to display the total number of votes in a Poll?

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

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,)))

如何使每个 questiontotal 票数,以便您可以在底部显示 total: 和此投票的总票数。

在这些情况下我通常会做的是在名为 total_votesQuestion 模型上添加一个 属性 来计算每个选择的总票数。您还可以利用 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 %}