在如下所示的detail_route
方法中,如何使用ordering
查询参数支持事件排序,如下所示:
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)
我尝试了以下内容,但没有任何内容被排序:
@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)
答案 0 :(得分:1)
汤男孩建议。您需要将EventDateTime添加到ItemViewSet中的ordering_fields。