DEV Community

Cover image for Day 23 of #100DaysOfCode: Create endpoints with query string on Django REST Framework
Jen-Hsuan Hsieh
Jen-Hsuan Hsieh

Posted on • Edited on

5

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

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!

AWS Q Developer image

Your AI Code Assistant

Ask anything about your entire project, code and get answers and even architecture diagrams. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Start free in your IDE

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay