[英]How can I get percentage?
我试图获得百分比,但我不知道如何为我的模型做这个。 我试着使用一些代码,但是我收到了错误。 我怎样才能获得模特的百分比?
models.py
class Choice(models.Model):
question = models.ForeignKey('Question', models.CASCADE)
message = models.CharField(max_length=1024)
ballots = models.IntegerField(null=True, blank =True)
views.py
def ReportList(request, id):
q = Question.objects.select_related().get(id = id)
queryset = Choice.objects.filter(question_id=id)
if not queryset:
return redirect ('error')
return render(request, 'polls/report.html', {'queryset': queryset, 'q': q})
HTML
{% for choice in queryset %}
<tr>
<td>{{ choice.message }}</td>
<td>{{ choice.ballots }}</td>
</tr>
{% endfor %}
我试着在models.py中使用这个代码,但我认为这是一种方式:
def get_percentage(self):
total_count = Choice.objects.annotate(sum('ballots'))
cnt = Choice.ballots.__float__()
perc = cnt * 100 / total_count
return perc
它可能不是最好的方法,但我只是在视图中进行计算并创建一个新字段
queryset = Choice.objects.filter(question_id=id)
total = float(sum(q.ballots for q in queryset)) / 100
for q in queryset:
q.pct = q.ballots/total
然后,您可以在模板中使用pct字段。
python有一个名为math module的内置模块。 使用将获得许多与数学运算相关的功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.