django: calculate percentage based on object count

南笙酒味 提交于 2019-12-06 11:27:48

Try this

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.

Update: Adding attribute to queryset is not easy and referring dicts in templates with key as variable is not possible too.

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 %}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!