我有以下模型:
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)
每个问题都有用户定义的选项。例如: 问题 - 最好的水果是什么?选项 - 苹果、橙子、葡萄。现在其他用户可以回答问题,他们的回答仅限于选项。
我有以下看法:
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 中的每个选项,我都会收到一个答案计数。例如:
问题 - 最好的水果是什么?
选项 - 葡萄、橙子、苹果
答案 - 葡萄:5 票,橙子 5 票,苹果 10 票。
计算每个选项在该问题总票数中的投票百分比的最佳方法是什么?
换句话说,我想要这样的东西:
答案 - 葡萄:5votes 25%votes,Orange 5votes 25%votes,Apple 10votes 50%votes。
测试.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.
更新:向查询集添加属性并不容易,并且在模板中以键作为变量引用字典也不可能。
因此解决方案是在 Option 模型中添加方法/属性以获取百分比作为
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
然后在模板中你可以使用所有这些方法来获取百分比
{% for opt in o %}
<tr>
<td>{{ opt }}</td>
<td>{{ opt.num_votes }}</td>
<td>{{ opt.get_percentage }}</td>
</tr>
{% endfor %}
