分别得到1、2、3、4、5星的平均值(1星% +2星% +3星% +4星% +5星%=100%) &

  • 本文关键字:100% 平均值 django
  • 更新时间 :
  • 英文 :


假设我给一个用户打了1星3次,2星1次,4星4次,5星10次。现在从这里任何人都可以找到总体平均评级,但我如何从总评级中获得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

相关内容

最新更新