thedeepfield
thedeepfield

Reputation: 6196

django: calculate percentage based on object count

I have the following models:

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 defined by the User. For Example: Question - What is the best fruit? Options - Apple, Orange, Grapes. Now other user's can Answer the question with their responses restricted to Options.

I have the following view:

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,
    })

For each option in o, I am receiving an answer count. For example:

Question - What is the best fruit?
Option - Grape, Orange, Apple
Answer - Grape: 5votes, Orange 5votes, Apple 10vote.

What is the best way to calculate the vote percentage for each option out of the total number of votes for that question?

In other words, I want something like this:

Answer - Grape: 5votes 25%votes, Orange 5votes 25%votes, Apple 10vote 50%votes.

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>

Upvotes: 2

Views: 12126

Answers (1)

Rohan
Rohan

Reputation: 53326

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.

Update: Adding attribute to queryset is not easy and referring dicts in templates with key as variable is not possible too.

So the solution would be add method/property in Option model to get percentage as

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

Then in template you can all this method to get percentage as

{% for opt in o %}
     <tr>
         <td>{{ opt }}</td>
     <td>{{ opt.num_votes }}</td>
     <td>{{ opt.get_percentage }}</td>
</tr>
 {% endfor %}

Upvotes: 3

Related Questions