本文主要是介绍APIView视图的序列化器继承ModelSerializser,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一、在serializser.py编写序列化器继承于ModelSerializser
from .models import Publishclass PublishSerializer(serializers.ModelSerializer):class Meta:model = Publishfields = "__all__"
二、在views.py编写类视图继承于APIView
from .models import Author, Publish
from .serializers import AuthorSerializer, PublishSerializerclass PublishView(APIView):def get(self, request):publishs = Publish.objects.all() #获取所有数据serializer = PublishSerializer(instance=publishs, many=True) #构建序列化器return Response(serializer.data)def post(self, request):serizlizer = PublishSerializer(data=request.data) #反序列化器#数据校验#验证通过 serializer.data#验证不通过 serializer.errorsif serizlizer.is_valid():# Author.objects.create(**serializer.validated_data) 这种原始传入数据的方法# return Respons("OK")serizlizer.save()return Response(serizlizer.data)else:return Response(serizlizer.errors)class PublishDetailView(APIView):def get(self, request, pk):publish = Publish.objects.get(pk=pk)serializer = PublishSerializer(instance=publish,many=False)return Response(serializer.data)def put(self, request, pk):publish = Publish.objects.get(pk=pk)serializer = PublishSerializer(instance=publish, data=request.data)if serializer.is_valid():serializer.save()return Response(serializer.data)else:return Response(serializer.errors)def delete(self, request, pk):Publish.objects.get(pk=pk).delete()return Response()
三、在urls.py增加路由表
from .views import PublishView, PublishDetailViewurlpatterns = [path('publish/', PublishView.as_view()),re_path('publish/(?P<pk>\d+)/', PublishDetailView.as_view())
]
四、测试
get post
http://127.0.0.1:8000/stu/publishput delete get
http://127.0.0.1:8000/stu/publish/1/
这篇关于APIView视图的序列化器继承ModelSerializser的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!