使用Django Rest Framework订购具有排序查询参数的detail_route

时间:2016-11-09 12:46:02

标签: python django django-rest-framework

在如下所示的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)

1 个答案:

答案 0 :(得分:1)

汤男孩建议。您需要将EventDateTime添加到ItemViewSet中的ordering_fields。