Django: DRF Filtering in views

Django: DRF Filtering in views

Table of contents

No heading

No headings in the article.

DRF creates endpoints for us to Create, Update, Retrieve & Delete models.

We have a model named Post

//models.py

from django.db import models
from django.contrib.auth import get_user_model

class Post(models.Model):
    title = models.CharField(max_length=250)
    date_time = models.DateTimeField()
    author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
    content = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.title

Now we create a serializer for model Post

//serializers.py

from rest_framework import serializers
from .models import Post

class PostSerializer(serializers.ModelSerializer):
    class Meta:
        model = Post
        fields = ("title","date_time","author","content")

Now we write views for Listing our Posts

//views.py

from rest_framework import generics
from rest_framework.permissions import IsAuthenticated

from .models import Post
from .serializers import PostSerializer

class PostListAPIView(generics.ListCreateAPIView):
    permission_classes = (IsAuthenticated,)
    queryset = Post.objects.all()
    serializer_class = PostSerializer

This PostListAPIView returns all the posts to anyone calling the API with this view.

But that's rarely the case. No one returns all the data on an API call.

Some data may be private, only relating to a single user.

In such cases. We can filter the data using the following way

In our case, we will only return the post created by the currently logged in user

//views.py
from rest_framework import generics
from rest_framework.permissions import IsAuthenticated

from .models import Post
from .serializers import PostSerializer

class PostListAPIView(generics.ListCreateAPIView):
    permission_classes = (IsAuthenticated,)

    serializer_class = PostSerializer

    def get_queryset(self):
        user = self.request.user
        return Post.objects.filter(author=user)

Now, this view returns only the posts written by the logged-in user.

This is how we filter the data in Django Rest Framework APIViews