1

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 a generic APIView class and I want it to use values as extracted from url kwargs, how would I do this?

4 Answers 4

3

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.

class ListProductsView(generics.ListCreateAPIView):
    serializer_class = ProductSerializer
    def get_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.

Sign up to request clarification or add additional context in comments.

Comments

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 :)

Comments

0

You can access below like

def get_queryset(self):
     data = self.kwargs.get("key-name")

Comments

0

If you want to use the get_queryset() method you can do something like this

def get_queryset(self):
    queryset = Model.objects.filter(parameter=self.kwargs['thing'])
    return queryset

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.