我想按平均评分对所有故事进行排序,当我输入url ... / stories?ordering = average_rating时,会出现错误:'list' object has no attribute 'model'
def get_queryset(self):
queryset = Story.objects.all()
ordering = self.request.query_params.get('ordering', None)
if ordering == 'average_rating':
return sorted(queryset, key=lambda s: s.average_rating)
return queryset
class Story(models.Model):
...
@property
def average_rating(self):
average_rating = self.ratings.all().aggregate(Avg('rating'))['rating__avg']
if average_rating is not None:
return round(float(average_rating), 2)
return None
答案 0 :(得分:1)
sorted(queryset, key=lambda s: s.average_rating)
将返回一个列表,而get_queryset
应返回一个queryset
您可以尝试以下操作:
def get_queryset(self):
queryset = Story.objects.all()
ordering = self.request.query_params.get('ordering', None)
if ordering == 'average_rating':
return queryset.annotate(rating_avg=Avg('ratings__rating')).order_by('rating_avg')
return queryset
答案 1 :(得分:1)
顾名思义,get_queryset
需要返回查询集而不是列表。
幸运的是,您可以在数据库中完成整个查询和排序;您不需要average_rating
方法。
queryset = Story.objects.annotate(average_rating= Avg('ratings__rating'))
ordering = self.request.query_params.get('ordering', None)
if ordering == 'average_rating':
queryset = queryset.order_by("average_rating")
return queryset