Adding more views to a Router or viewset (Django-Rest-Framework)

后端 未结 4 581
既然无缘
既然无缘 2021-02-05 04:48

Essentially, I\'m trying to find a good way to attach more views to a Router without creating a custom Router. What\'s a good way to accomplish this?

He

4条回答
  •  花落未央
    2021-02-05 05:01

    You can now do this with the list_route and detail_route decorators: http://www.django-rest-framework.org/api-guide/viewsets/#marking-extra-actions-for-routing

    For example:

    from rest_framework.decorators import list_route
    from rest_framework.response import Response
    ...
    
    class MyObjectsViewSet(viewsets.ViewSet):
        ...
    
        @list_route()
        def locations(self, request):
            queryset = get_locations()
            serializer = LocationSerializer(queryset, many=True)
            return Response(serializer.data)
    

提交回复
热议问题