How To Access Url Kwargs In Generic Api Views (listcreateapiview To Be More Specific) In Django Rest Framework?
How to access url kwargs in generic API views (ListCreateAPIView to be more specific) in django rest framework, for example say I want to override the get_queryset() method inside
Solution 1:
Answers from leelum1 and aman kumar helped me a lot, since I had the same question. I would add a particular example of how I used their answers. In the code below I try to obtain all the products that have as category
attribute the same string passed on the cat
variable from the url.
classListProductsView(generics.ListCreateAPIView):
serializer_class = ProductSerializer
defget_queryset(self):
queryset = Product.objects.filter(category=self.kwargs['cat'])
return queryset
That solved my problem of filtering objects by using variables from the url.
Solution 2:
I spend a lot of time finding the answer to this question. Finally found it in my old written code. It works like a charm.
self.request.query_params.get('<name>')
I hope that is someone is still looking to get an answer this will help you :)
Solution 3:
You can access below like
defget_queryset(self):
data = self.kwargs.get("key-name")
Solution 4:
If you want to use the get_queryset() method you can do something like this
defget_queryset(self):
queryset = Model.objects.filter(parameter=self.kwargs['thing'])
return queryset
Post a Comment for "How To Access Url Kwargs In Generic Api Views (listcreateapiview To Be More Specific) In Django Rest Framework?"