2

私は次のモデルを持っています:

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)

それぞれQuestionOptionsユーザーによって定義されています。例: 質問 - 最高の果物は何ですか? オプション - アップル、オレンジ、ブドウ。これで、他のユーザーは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% 票。

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>
4

1 に答える 1

3

これを試して

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 に属性を追加するのは簡単ではなく、変数としてキーを持つテンプレートで辞書を参照することもできません。

したがって、解決策は、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 %}
于 2013-10-10T04:46:09.617 に答える