Как отобразить общее количество голосов в опросе?

У меня есть простое приложение для голосования.

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

Как сделать так, чтобы total количество голосов для каждого question можно было вывести 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 %}
Вернуться на верх