Django rest framework: query parameters in detail_route

后端 未结 2 1872
醉酒成梦
醉酒成梦 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 15:51
    1. For endpoint url as: (using Django REST ViewSets)

    {mysite}/users/{pk}/password/{id}

    for this to work in my viewsets i did:

    class UsersViewSet(viewsets.ModelViewSet):
        queryset = User.objects.all()
        serializer_class = UserSerializer
    
    
    @detail_route(url_path='password')
    def password(self, request,pk=None):
        return HttpResponse("Wow! It Works")
    

    from above you can retrieve id from url via pk variable.

    1. For EndPoint Url as

      {mysite}/users/{pk}/password/{number}

    Change the above password method to

    @detail_route(url_path='password/(?P<number>[0-9]+)')
    def password(self, request,pk=None, number=None):
        return HttpResponse("Wow! It Again Works")
    
    0 讨论(0)
  • 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<chapter_id>[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})
    
    0 讨论(0)
提交回复
热议问题