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

Time:05-27

I have a simple voting application.

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 >{{ question.question_text }}</h1>

<ul >
    {% for choice in question.choice_set.all %}
    <li >
        {{ choice.choice_text }}  <span >{{ choice.votes }} vote{{ choice.votes | pluralize }}</span>
    </li>
    {% endfor %}
</ul>

<a  href="{% url 'polls:index' %}">Back To Polls</a>
<a  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,)))

How to make the total number of votes for each question so that you can display total: and the total number of votes for this poll at the bottom.

CodePudding user response:

What I would normally do in these situations is to add a property on the Question model called total_votes which calculates the total votes for every choice. You can also leverage on some aggregation functions in 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']

Then you can use total_votes property as you would an actual attribute of a model instance. Caveat: impossible to use in querysets (filtering and such).

To display:

{% extends 'base.html' %}
{% block content %}
<h1 >{{ question.question_text }}</h1>
<h2 >Total votes: {{ question.total_votes }}</h2>

<ul >
    {% for choice in question.choice_set.all %}
    <li >
        {{ choice.choice_text }}  <span >{{ choice.votes }} vote{{ choice.votes | pluralize }}</span>
    </li>
    {% endfor %}
</ul>

<a  href="{% url 'polls:index' %}">Back To Polls</a>
<a  href="{% url 'polls:detail' question.id %}">Vote again?</a>
{% endblock %}
  • Related