基于GenericAPIView写的接口
作者:互联网
# views.py class Book2View(GenericAPIView): #queryset要传queryset对象,查询了所有的图书 # serializer_class使用哪个序列化类来序列化这堆数据 queryset=Book.objects # queryset=Book.objects.all() serializer_class = BookSerializer def get(self,request): book_list=self.get_queryset() book_ser=self.get_serializer(book_list,many=True) return Response(book_ser.data) def post(self,request): book_ser = self.get_serializer(data=request.data) if book_ser.is_valid(): book_ser.save() return Response(book_ser.data) else: return Response({'status':101,'msg':'校验失败'}) class Book2DetailView(GenericAPIView): queryset = Book.objects serializer_class = BookSerializer def get(self, request,pk): book = self.get_object() book_ser = self.get_serializer(book) return Response(book_ser.data) def put(self, request,pk): book = self.get_object() book_ser = self.get_serializer(instance=book,data=request.data) if book_ser.is_valid(): book_ser.save() return Response(book_ser.data) else: return Response({'status': 101, 'msg': '校验失败'}) def delete(self,request,pk): ret=self.get_object().delete() return Response({'status': 100, 'msg': '删除成功'}) #url.py # 使用GenericAPIView重写的 path('books2/', views.Book2View.as_view()), re_path('books2/(?P<pk>\d+)', views.Book2DetailView.as_view()),
标签:GenericAPIView,基于,ser,get,self,接口,book,data,Response 来源: https://www.cnblogs.com/dzs894330350/p/16104776.html