Note that there are some explanatory texts on larger screens.

plurals
  1. POdjango: calculate percentage based on object count
    primarykey
    data
    text
    <p>I have the following models:</p> <pre><code>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) </code></pre> <p>Each <code>Question</code> has <code>Options</code> defined by the User. For Example: Question - What is the best fruit? Options - Apple, Orange, Grapes. Now other user's can <code>Answer</code> the question with their responses restricted to <code>Options</code>.</p> <p>I have the following view:</p> <pre><code>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, }) </code></pre> <p>For each option in o, I am receiving an answer count. For example: </p> <p>Question - What is the best fruit?<br> Option - Grape, Orange, Apple<br> Answer - Grape: 5votes, Orange 5votes, Apple 10vote.</p> <p>What is the best way to calculate the vote percentage for each option out of the total number of votes for that question? </p> <p>In other words, I want something like this:</p> <p>Answer - Grape: 5votes 25%votes, Orange 5votes 25%votes, Apple 10vote 50%votes.</p> <p>test.html </p> <pre><code>{% for opt in o %} &lt;tr&gt; &lt;td&gt;{{ opt }}&lt;/td&gt; &lt;td&gt;{{ opt.num_votes }}&lt;/td&gt; &lt;td&gt;PERCENT GOES hERE&lt;/td&gt; &lt;/tr&gt; {% endfor %} &lt;div&gt; {% for key, value in perc_dict.items %} {{ value|floatformat:"0" }}% {% endfor %} &lt;/div&gt; </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload