django:根据对象数计算百分比 [英] django: calculate percentage based on object count
问题描述
我有以下模型:
class Question(models.Model):
question = models.CharField(max_length=100)
class Option(models.Model):
question = models.ForeignKey(Question)
value = models.CharField(max_length=200)
class Answer(models.Model):
option = models.ForeignKey(Option)
每个问题
具有用户定义的选项
。例如:问题-最好的水果是什么?选项-苹果,橙,葡萄。现在其他用户可以答案
问题,其回答仅限于选项
。
Each Question
has Options
defined by the User. For Example: Question - What is the best fruit? Options - Apple, Orange, Grapes. Now other user's can Answer
the question with their responses restricted to Options
.
我有以下视图:
def detail(request, question_id):
q = Question.objects.select_related().get(id=question_id)
a = Answer.objects.filter(option__question=question_id)
o = Option.objects.filter(question=question_id).annotate(num_votes=Count('answer'))
return render(request, 'test.html', {
'q':q,
'a':a,
'o':o,
})
对于o中的每个选项,我都会收到一个答案计数。例如:
For each option in o, I am receiving an answer count. For example:
问题-最好的水果是什么?
选项-葡萄,橙,苹果
答案-葡萄:5票,橙色5票,苹果10票。
Question - What is the best fruit?
Option - Grape, Orange, Apple
Answer - Grape: 5votes, Orange 5votes, Apple 10vote.
从该问题的总票数中计算每个选项的投票百分比的最佳方法是什么?
What is the best way to calculate the vote percentage for each option out of the total number of votes for that question?
换句话说,我想要这样的东西:
In other words, I want something like this:
答案-葡萄:5票25%票,橙色5票25%票,苹果10票50%票。
Answer - Grape: 5votes 25%votes, Orange 5votes 25%votes, Apple 10vote 50%votes.
test.html
test.html
{% for opt in o %}
<tr>
<td>{{ opt }}</td>
<td>{{ opt.num_votes }}</td>
<td>PERCENT GOES hERE</td>
</tr>
{% endfor %}
<div>
{% for key, value in perc_dict.items %}
{{ value|floatformat:"0" }}%
{% endfor %}
</div>
推荐答案
尝试一下
total_count = Answer.objects.filter(option__question=question_id).count()
perc_dict = { }
for o in q.option_set.all():
cnt = Answer.objects.filter(option=o).count()
perc = cnt * 100 / total_count
perc_dict.update( {o.value: perc} )
#after this the perc_dict will have percentages for all options that you can pass to template.
更新:向queryset添加属性并不容易,而且用键作为变量引用模板中的字典也是不可能的。
Update: Adding attribute to queryset is not easy and referring dicts in templates with key as variable is not possible too.
所以解决方案是在 Option
模型中添加方法/属性,以获取
So the solution would be add method/property in Option
model to get percentage as
class Option(models.Model):
question = models.ForeignKey(Question)
value = models.CharField(max_length=200)
def get_percentage(self):
total_count = Answer.objects.filter(option__question=self.question).count()
cnt = Answer.objects.filter(option=self).count()
perc = cnt * 100 / total_count
return perc
然后,在模板中,您可以使用所有这种方法来获取百分比,如下所示:
Then in template you can all this method to get percentage as
{% for opt in o %}
<tr>
<td>{{ opt }}</td>
<td>{{ opt.num_votes }}</td>
<td>{{ opt.get_percentage }}</td>
</tr>
{% endfor %}
这篇关于django:根据对象数计算百分比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!