Oskar Oskar - 1 month ago 16
Python Question

Order detail_route with ordering query parameter using Django Rest Framework

In a

detail_route
method like the following, how would I support ordering of the events using the
ordering
query parameter like this:

http://localhost.com/items/123/events?ordering=EventDateTime

class ItemViewSet(viewsets.ModelViewSet):

queryset = Item.objects.all()
serializer_class = ItemSerializer
filter_backends = (
filters.OrderingFilter
)
ordering_fields = ('Label')

@detail_route()
def events(self, request, pk=None):
item = self.get_object()
events = item.events.all()
page = self.paginate_queryset(events)
if page is not None:
serializers = EventSerializer(page, many=True, context={'request': request})
return self.get_paginated_response(serializers.data)
serializers = EventSerializer(events, many=True, context={'request': request})
return Response(serializers.data)


I've tried the following but nothing gets sorted:

@detail_route()
def events(self, request, pk=None):
item = self.get_object()
events = filters.OrderingFilter().filter_queryset(request, item.events.all(), self)
page = self.paginate_queryset(events)
if page is not None:
serializers = EventSerializer(page, many=True, context={'request': request})
return self.get_paginated_response(serializers.data)
serializers = EventSerializer(events, many=True, context={'request': request})
return Response(serializers.data)

Answer

As soup boy suggested. You need to add EventDateTime to ordering_fields in the ItemViewSet.