Issue
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.
Solution
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
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.