django:根据对象计数计算百分比

2023-11-29

我有以下型号:

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由用户定义。例如:问题 - 最好的水果是什么?选项 - 苹果、橙子、葡萄。现在其他用户可以Answer他们的回答仅限于问题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 中的每个选项,我都会收到答案计数。例如:

问题:最好的水果是什么?
选项 - 葡萄、橙子、苹果
答案 - 葡萄:5票,橙子5票,苹果10票。

计算每个选项在该问题总票数中的投票百分比的最佳方法是什么?

换句话说,我想要这样的东西:

答案——葡萄:5票25%票,橙子5票25%票,苹果10票50%票。

测试.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>

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.

更新:向查询集添加属性并不容易,并且用键作为变量引用模板中的字典也是不可能的。

所以解决方案是添加方法/属性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 %}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

django:根据对象计数计算百分比 的相关文章

随机推荐