DEV Community

loading...
Cover image for Day 23 of #100DaysOfCode: Create endpoints with query string on Django REST Framework

Day 23 of #100DaysOfCode: Create endpoints with query string on Django REST Framework

jenhsuan profile image Jen-Hsuan Hsieh ・2 min read

Introduction

On the last post, we have learned how to create endpoints on DRF. What if we want to create endpoints with query string? We can use the filter to filter the result.

Overview

Implementation

  • This is an example for passing a category parameter to get articles

Model

class Article(models.Model):
    title = models.CharField(max_length = 200)
    subtitle = models.CharField(max_length = 200)
    image = models.TextField()
    url =models.TextField()
    name = models.CharField(max_length = 64)
    time = models.DateField()
    readtime = models.CharField(max_length = 64)
    CATEGORY = Choices((0, 'devto', _('devto')), (1, 'medium', _('medium')))
    category = models.IntegerField(choices=CATEGORY, default=CATEGORY.devto)
    description = models.CharField(max_length = 64, default='')

    def __str__(self):
        return f"{self.id} - {self.title}, {self.subtitle}, {self.image}, {self.name}, {self.url}, {self.time}, {self.readtime}, {self.category}"

Enter fullscreen mode Exit fullscreen mode

Serializers

from rest_framework import serializers
from .models import Article

class ArticleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Article
        fields = '__all__'
Enter fullscreen mode Exit fullscreen mode

Views

class ArticleByCategoryViewSet(generics.ListAPIView):
    permission_classes = (permissions.AllowAny,)
    serializer_class = ArticleSerializer
    http_method_names = ['get']

    def get_queryset(self):
        queryset = Article.objects.all()
        category = self.request.query_params.get('category', None)
        if category is not None:
            queryset = queryset.filter(category=category)
        return queryset
Enter fullscreen mode Exit fullscreen mode

URLs

urlpatterns = [
    ...
    path("api/articles", ArticleByCategoryViewSet.as_view(), name='articles'),
    ...
]
Enter fullscreen mode Exit fullscreen mode

Testing

Test the endpoint by Postman
Alt Text

That's it

Articles

There are some of my articles. Feel free to check if you like!

Discussion (0)

pic
Editor guide