Django rest framework: query parameters in detail_route

后端 未结 2 1871
醉酒成梦
醉酒成梦 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[0-9]+)')
    def password(self, request,pk=None, number=None):
        return HttpResponse("Wow! It Again Works")
    

提交回复
热议问题