1

I am trying to filter my 'Posts' model by a parameter passed into a query string in the url. If this parameter is not given, I want the url to just return all posts.

To my (obviously incorrect) understanding, the following is how it should work:

urls.py:

path('feed?category=<str:category>', views.Posts.as_view())

views.py:

def Posts(APIView):
    def get(self, request, **kwargs):
        if self.kwargs['category']:
            queryset = Post.objects.filter(category_name = self.kwargs['category'])
        else:
            queryset = Post.objects.all()

With the above code, I would expect that by requesting a url .../feed, the view would set the queryset to all posts, however if I entered a url .../feed?category=x it would only return posts of this category.

Currently, the program does not function as such. How would I accomplish this functionality?

Thanks, Grae

1
  • path only checks the path of the URL, the part after the ? is not the path, that is the query string, so you can not filter with that in the path. Commented Sep 30, 2020 at 18:36

1 Answer 1

2

path only checks the path of the URL, the part after the ? is not the path, that is the query string [wiki], so you can not filter with that in the path. The query string is stored in request.GET a dictionary-like object.

You thus define the path as:

path('feed/', views.PostView.as_view())

and in the view, you can filter with:

def PostView(APIView):
    model = Post

    def get_queryset(self, *args, **kwargs):
        queryset = super().get_queryset(*args, **kwargs)
        if 'category' in self.request.GET:
            return queryset.filter(category_name=self.request.GET['category'])
        return queryset

Note: In Django, class-based views (CBV) often have a …View suffix, to avoid a clash with the model names. Therefore you might consider renaming the view class to PostView, instead of Posts.

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

3 Comments

If the query string is a dictionary item then can I not access the 'category' variable using self.kwargs['category']?
Would it work to instead use: if 'category' in self.request.kwargs ?
@GraeCumming: no, a request object has no .kwargs, only the view has. The self.kwargs do not contain the items in the querystring, only the path variables.

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.