Django rest framework: query parameters in detail_route

后端 未结 2 1882
醉酒成梦
醉酒成梦 2021-02-18 15:33

I have following ViewSet:

class BookViewSet(DefaultsMixin, viewsets.ModelViewSet):
   queryset = Book.objects.all()
   serializer_class = BookSerializer

   @det         


        
2条回答
  •  悲哀的现实
    2021-02-18 16:11

    you can do this adding url_path in the detail_route like:

    @detail_route(url_name='chapter', url_path='chapter/(?P[0-9]+)')
    def chapter(self, request, pk=None, chapter_id=None):
       queryset = Chapter.objects.filter(book__pk=pk)
       serializer = ChpaterSerializer(queryset,
                       context={'request':request},
                       many=True)
       return Response(serializer.data)
    

    Note that the name of the url in the default router defaults to the url_path argument if it is provided. So the view name would inlcude the query parameter string. By specifying the url_name argument, you can simplify that. I would recommend to use the method name there, which is the default if url_path is not specified. With that, you can reverse the url with

    reverse('book-chapter', kwargs={'pk': 1, 'chapter_id': 4})
    

提交回复
热议问题