Home > Blockchain >  Get 1,2,3,4,5 star average individually (1star% 2star% 3star% 4star% 5star%=100%)
Get 1,2,3,4,5 star average individually (1star% 2star% 3star% 4star% 5star%=100%)

Time:05-22

Suppose i have rated a user with 1 star 3 times, 2star 1times, 4star 4 times, 5star 10times.now from here anyone can find out overall average rating but how can i get the percentage of 1star,2star ,3star,4star and 5star from total rating #show it on a django way

    rating = Rating.objects.filter(activity__creator=u)
    one_star_count = rating.filter(star='1').count()
    two_star_count = rating.filter(star='2').count()
    three_star_count = rating.filter(star='3').count()
    four_star_count = rating.filter(star='4').count()
    five_star_count = rating.filter(star='5').count()

    total_stars_count = one_star_count   two_star_count  \
    three_star_count   four_star_count  five_star_count

CodePudding user response:

Create in your User model methods, that count the precentage and then simply use it as needed:

class User(...):
    ...
    def count_star_precentage(self, star):
        return (Rating.objects.filter(activity__creator=self, star=star).count() / self.all_ratings().count()) * 100

    def all_ratings(self):
        return Rating.objects.filter(activity__creator=self)

With them you can get precentage with simple call:

 user = User.objects.get(id=some_id)
 user.count_star_precentage(3)    # it will give the percent of total ratings with 3 star given by that user
  • Related