
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:
Post a Comment