GenericAPIView的接口实现调用方法学习


GenericAPIView的接口实现调用方法学习


一、在serializser.py编写序列化器继承于ModelSerializser

       序列化器没变化!

二、在views.py编写类视图继承于GenericAPIView
from rest_framework.generics import GenericAPIView
class PublishView(GenericAPIView):
   queryset = Publish.objects
   serializer_class = PublishSerializer
   def get(self, request):
       #serializer = self.serializer_class(instance = self.queryset,many=True)
       #serializer = self.get_serializer_class()(instance = self.queryset,many=True)
       serializer = self.get_serializer(instance = self.get_queryset(),many=True)
       return Response(serializer.data)

   def post(self,request):
        serizlizer = self.get_serializer(data=request.data)    #反序列化器
        #数据校验
        #验证通过   serializer.data
        #验证不通过  serializer.errors
        if 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(GenericAPIView):
    queryset = Publish.objects
    serializer_class = PublishSerializer
    def get(self, request, pk):
            serializer = self.get_serializer(instance=self.get_object(), many=False)
            return Response(serializer.data)
    def put(self, request, pk):
        serializer = self.get_serializer(instance=self.get_object(), data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        else:
            return Response(serializer.errors)
    def delete(self, request, pk):
        self.get_object().delete()
        return Response()

三、在urls.py增加路由表
from .views import PublishView, PublishDetailView

urlpatterns = [
   path('publish/', PublishView.as_view()),
   re_path('publish/(?P\d+)/', PublishDetailView.as_view())
]

四、测试

get post
http://127.0.0.1:8000/stu/publish

put delete get
http://127.0.0.1:8000/stu/publish/1/

你可能感兴趣的:(学习,python,开发语言)