Searching...
Tuesday, November 2, 2021

CRUD Pagination with APIVews in Django Rest Framework - tutorial

7:35 PM
This session I will sahre ebook and tutorial Script pagination example with class Views with python drf, like from documentation from django, Django provides high-level and low-level ways to help you manage paginated data – that is, data that’s split across several pages, with “Previous/Next” links or you can custome paging scripts. DRF can also write our API views using class-based views, rather than function based views. As we'll see this is a powerful pattern that allows us to reuse common functionality, documentation
this script seriallizer from model, todo like this simple example.

Seriallizers
 class ContentSerializer(serializers.ModelSerializer):
    category=serializers.SerializerMethodField(read_only=True)
    def get_category(self,obj):
        data={
            'name':obj.category.category
        }
        return data
    author=serializers.SerializerMethodField(read_only=True)
    def get_author(self,obj):
        data={
            'name':obj.author.username
        }
        return data
 
if you want todo use authentication with token, please.. install modul package rest_framework_simplejwt then config in the file setting.py, and you can do this like for the example: this example of simple script code for pagination and methode search and for detail for crud
this documentation Views Class
import imp
from django import views
from django.http import Http404
from rest_framework.views import APIView
from rest_framework.pagination import LimitOffsetPagination
from rest_framework.response import Response
from rest_framework import status,serializers
from rest_framework_simplejwt.authentication import JWTAuthentication
from backend.models import ContentModel
from api.Serializerapi.serializers import ContentSerializer
from rest_framework.permissions import IsAuthenticated
from django.db.models import Q,F,Sum, Count

class GetPostContent(APIView, LimitOffsetPagination):
    # authentication_classes=[JWTAuthentication]
    permission_classes=[IsAuthenticated]
    
    def get(self,request,format=None):
        obj=ContentModel.objects.all()
        cari=request.GET.get('q')
        if cari:
            obj=obj.filter(Q(judul__icontains=cari))

        results=self.paginate_queryset(obj, request, view=self)
        serializers=ContentSerializer(results, many=True)
        return self.get_paginated_response(serializers.data)
    
    def post(self,request,format=None):
        objseializer=ContentSerializer(data=request.data)
        if objseializer.is_valid():
            objseializer.save()
            return Response (objseializer.data,status=status.HTTP_200_OK)
        return Response (objseializer.errors,status=status.HTTP_204_NO_CONTENT)

class DetailGetContent(APIView):
    # authentication_classes=[JWTAuthentication]
    permission_classes=[IsAuthenticated]

    def get_object(self,pk):
        try:
            return ContentModel.objects.get(pk=pk)
        except ContentModel.DoesNotExist:
            raise Http404
    def get(self,request,pk,format=None):
        obj=self.get_object(pk)
        objserializer=ContentSerializer(obj)
        return Response(objserializer.data,status=status.HTTP_200_OK)
    def put(self,request,pk,format=None):
        obj=self.get_object(pk)
        objserializer=ContentSerializer(obj, data=request.data)
        if objserializer.is_valid():
            objserializer.save()
            return Response(objserializer.data,status=status.HTTP_202_ACCEPTED)
        return Response(objserializer.errors,status=status.HTTP_304_NOT_MODIFIED)
  
  
end for route path you can do or coustemize in file url.py, for this cas i use like this
 path('v1/contentget/',content_apiV1_jwt.GetPostContent.as_view()),
 path('v1/contentget/',content_apiV1_jwt.DetailGetContent.as_view()),

0 comments: