DEV Community

Serhat Teker
Serhat Teker

Posted on • Originally published at tech.serhatteker.com on

3 1

How to filter your query with params in Django Rest - Part I

Intro

Let's assume that I have an endpoint like below, linked to
usual generics.ListCreateAPIView:

  • /api/articles/ - GET, POST
# articles/views.py
from rest_framework import generics

from src.articles.models import Article
from src.articles.serializer import ArticleSerializer


class ArticleListView(generics.ListCreateAPIView):
    queryset = Article.objects.all()
    serializer_class = ArticleSerializer
Enter fullscreen mode Exit fullscreen mode

As you may already know you can fetch all articles via GET and post a new article via POST with required data in the body.

OK, the question is how can I filter articles against queryset parameters? Like;

Solution

The default behavior of REST framework's generic list views is to return the entire queryset for a model manager. We should overwrite the default get_queryset method;

# articles/views.py
from rest_framework import generics

from src.articles.models import Article
from src.articles.serializer import ArticleSerializer


class ArticleListView(generics.ListCreateAPIView):
    queryset = Article.objects.all()
    serializer_class = ArticleSerializer
    region_separator = ","

    def get_queryset(self):
        """
        Optionally restricts the returned articles to given regions,
        by filtering against a `regions` query parameter in the URL.
        """
        regions = self.request.query_params.get("regions", None)
        if regions:
            qs = Article.objects.filter()
            for region in regions.split(self.region_separator):
                qs = qs.filter(regions__code=region)

            return qs

        return super().get_queryset()
Enter fullscreen mode Exit fullscreen mode

It filters articles when regions query param provided, when there is no param it returns all articles.

All done!

Top comments (0)

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay