【问题标题】:How to display the total number of votes in a Poll?如何在投票中显示总票数?
【发布时间】:2022-08-05 22:46:27
【问题描述】:

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

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: 和此投票的总投票数。

  • 你能分享你的观点吗,你可以使用model.objects.count()。

标签: python django django-models django-views django-templates


【解决方案1】:

在这些情况下,我通常会在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 %}

【讨论】:

    猜你喜欢
    • 2023-03-30
    • 1970-01-01
    • 2011-09-30
    • 2012-03-15
    • 1970-01-01
    • 2011-09-30
    • 2021-12-09
    • 1970-01-01
    • 2019-04-03
    相关资源
    最近更新 更多