How Do I Get Django Poll Votes In Percentage Format?

I used the tutorial to create a polling app...and I've been expanding on it...I've got it working...but I can't figure out how to turn the votes into percentages...

I have tried to do something like...

def percentage(self):
     return 100 * (self.votes) / (self.survey)

But this isn't working...

My models look like...

class Choice(models.Model):
 
    choice = models.TextField(max_length=264,blank=True,null=True,unique=False)
    survey = models.ForeignKey("Survey",on_delete=models.CASCADE,related_name="choice_survey")
    votes = models.IntegerField(default=0)

class Survey(models.Model):
 
    survey_name = models.CharField(max_length=255,blank=True,null=True,unique=False)
    survey_type = models.CharField(choices=STATUS_CHOICES8,blank=True,max_length=300)

I've seen examples of annotate and I've played with them as well. Do I need to keep track of the total number of votes as an attribute? The other examples I've seen are all foreignkey. I can totally get the number of votes by getting the integerfield. I just can't seem to figure out how to convert this into a percentage.

Thanks in advance for any suggestions.

A percentage is a fraction of a particular value. In this case, you need something to compare the number of votes for this choice against - eg, the number of all votes for all choices.

Assuming you have a very simply survey (eg, only one multiple-choice question) then you can obtain this number by

def percentage(self):
     total_votes = Choice.objects.filter(survey=self.survey).count()
     return (self.votes / total_votes) * 100

If you have many questions in your survey, then you'll need an intermediate model, like Question, so that a survey holds many questions, and they, in turn, have many choices. Then you can do the same thing with Question that we have with survey above.

I was able to solve my issue by reference this previously documented issue on SO. How do I call a custom method on a model with a template in Django?

I was able to answer my question leveraging the solution documented here....

How do I call a custom method on a model with a template in Django?

My final answer looks like....

def percentage(self):
    total = 0.0
    for choice in self.poll.choice_set.all():
        total = total + choice.votes
    return (self.votes/total)*100
Back to Top