分别得到1,2,3,4,5星平均(1星%+2星%+3星%+4星%+5星%=100%)
Get 1,2,3,4,5 star average individually (1star% +2star% +3star% +4star% +5star%=100%)
假设我给一个用户评分 1 星 3 次,2 星 1 次,4 星 4 次,5 星 10times.now 从这里任何人都可以找出总体平均评分,但我如何获得 1 星、2 星的百分比,3星,4星和5星总评分
#以django方式显示它
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
在您的 User
模型方法中创建计算百分比的方法,然后根据需要简单地使用它:
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)
有了他们,您可以通过简单的调用获得百分比:
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
假设我给一个用户评分 1 星 3 次,2 星 1 次,4 星 4 次,5 星 10times.now 从这里任何人都可以找出总体平均评分,但我如何获得 1 星、2 星的百分比,3星,4星和5星总评分 #以django方式显示它
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
在您的 User
模型方法中创建计算百分比的方法,然后根据需要简单地使用它:
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)
有了他们,您可以通过简单的调用获得百分比:
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