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 Sean 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}"

Serializers

from rest_framework import serializers
from .models import Article

class ArticleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Article
        fields = '__all__'

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

URLs

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

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!

Posted on by:

jenhsuan profile

Sean Hsieh

@jenhsuan

5+ year work experience in the software engineering field. Near 2-year work experience with front-end JavaScript framework like React.js, Knockout.js. and Microsoft solution.

Discussion

markdown guide