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
- The roles between endpoints and the database includes models, serializers, views, and urls
- You can also refer to https://medium.com/a-layman/build-single-page-application-with-react-and-django-part-4-create-endpoints-to-manipulate-13aefa60625b
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
That's it
Articles
There are some of my articles. Feel free to check if you like!
- My blog-posts for software developing: https://medium.com/a-layman
- My web resume: https://jenhsuan.github.io/ALayman/cover.html
- Facebook page: https://www.facebook.com/imalayman
Top comments (0)