desc中的模型的order_by @property不起作用

时间:2019-10-02 09:42:00

标签: python django django-rest-framework

我创建了自己的订购类,当我想按受欢迎程度进行订购时,它只会按desc中的评分将所有故事按顺序订购

class CustomOrdering(OrderingFilter):
    allowed_filters = ['top']

    def get_ordering(self, request, queryset, view):
        ...

    def filter_queryset(self, request, queryset, view):
        ordering = self.get_ordering(request, queryset, view)

        if ordering:
            ordering = ['-rating']

        if ordering:
            return queryset.order_by(*ordering)

        return queryset

models.py

class Story(models.Model):
    ....
    @property
    def average_rating(self):
        average_rating = self.rating_set.all().aggregate(Avg('rating'))['rating__avg']
        if average_rating is not None:
            return round(float(average_rating), 2)

0 个答案:

没有答案