I used the tutorial to create a voting app…and have been extending it…it’s working…but I can’t figure out how to convert the votes to percentages. ..
I tried to do something like…
def percentage (self): return 100 * (self.votes) / (self.survey)
But this doesn’t work…
My model looks like this…
class Choice(models.Model): select = models.TextField(max_length=264,blank=True,null=True,unique=False) survey = models.ForeignKey("Survey",on_delete=models.CASCADE,related_name="choice_survey") vote = 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 have seen examples of annotations and have played with them. Should the total vote count be tracked as an attribute? All the other examples I’ve seen are foreign keys. By getting the integer field, you can get the vote count perfectly. I’m not sure how to convert this to a percentage.
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
Answered By – Steve Smith
Answer Checked By – Clifford M. (Easybugfix Volunteer)