2013-10-10 20 views
1

我有以下型號計算百分比:Django的:基於對象計數

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每個選項,我收到了一個答案計數。例如:

問題 - 什麼是最好的水果?
Option - Grape,Orange,Apple
答案 - 葡萄:5票,橙色5票,蘋果10票。

在該問題的總票數中,計算每個選項的投票百分比的最佳方式是什麼?

換句話說,我想是這樣的:

答案 - 葡萄:5votes 25張%的選票,橙5votes 25張%的選票,蘋果10vote 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> 

回答

2

試試這個

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 %} 
+0

對不起,我不完全理解如何將其整合到我現有的代碼中。我是否用這個取代了我的觀點中的所有內容?我將如何在我的模板中顯示這個? – thedeepfield

+0

我已更新我的問題以顯示我的模板。你的解決方案的作品,但它似乎與我在我的模板中分開.. – thedeepfield

+0

@thedeepfield,檢查更新的答案。 – Rohan