Different ordering fields for ViewSets actions

Viewed 469

I have a viewset lets say TestingViewSet which has a default ordering field id.

class TestingViewSet(viewsets.ReadOnlyViewSet):
  filter_backends = (
    django_filters.rest_framework.DjangoFilterBackend,
    filters.OrderingFilter,
  )
   
ordering = ('id',)

But there as some custom action views that uses the super(TestingViewSet).list that i want to change the ordering field for them conditionally e.x

 def distinct_list(self, request):
    return super(TestingViewSet, self).list(request)

Is there a way like to change the ordering field of function distinct_list only?

1 Answers

You can assign the value to self.ordering as

class TestingViewSet(viewsets.ReadOnlyViewSet):
    filter_backends = (
        django_filters.rest_framework.DjangoFilterBackend,
        filters.OrderingFilter,
    )

    ordering = ('id',)

    @action(...)
    def distinct_list(self, request):
        self.ordering = ("some_other_field",)
        # or
        self.ordering = ()  # to remove the ordering
        return super().list(request, *args, **kwargs)
Related