我有一個簡單的投票應用程式。
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:在底部顯示此投票的總票數。
uj5u.com熱心網友回復:
在這些情況下,我通常會在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 %}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/482663.html
