私は次のモデルを持っています:
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)
それぞれQuestion
が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% 票。
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>