0

I created own ordering class and when i want to order by popularity, it brings only all stories ordering by rating in 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)
Danabek Duisekov
  • 315
  • 5
  • 12
  • Shouldn't you rewrite it to `if not ordering:`? Currently you set `ordering = ['-created_at']` *if* the `ordering` is set. – Willem Van Onsem Oct 02 '19 at 09:43
  • You can't order by using `properties` - ordering happens at the database level, you'll first need to annotate the queryset with that calculation before ordering by - either that or you can transform the queryset into a list and then perform the ordering in python. https://stackoverflow.com/questions/4175749/sorting-a-django-queryset-by-a-property-not-a-field-of-the-model and https://stackoverflow.com/questions/1396264/how-to-sort-by-annotated-count-in-a-related-model-in-django have examples – henriquesalvaro Oct 02 '19 at 15:56

0 Answers0