基于两个视图基类GenericAPIView,APIView
class Bookserializers(serializers.ModelSerializer):
# name = serializers.CharField()
# price = serializers.CharField()
# publish_id = serializers.CharField(write_only=True)
# Authors = serializers.ListField(write_only=True)
Authors_list = serializers.ListField(read_only=True)
publish_dict = serializers.DictField(read_only=True)
class Meta:
model = Book
# feilds = "__all__"
fields = ['name', 'price', 'publish', 'Authors', 'Authors_list', 'publish_dict']
extra_kwargs = {
}
class BookAPIView(APIView):
def get(self, request):
book = Book.objects.all()
ser = Bookserializers(instance=book, many=True)
return Response({"code": 200, "msg": "查询成功", "result": ser.data})
def post(self, request):
ser = Bookserializers(data=request.data)
if ser.is_valid():
ser.save()
return Response({"code": 200, "msg": "增加成功", "result": ser.data})
return Response({"code": 200, "msg": "增加失败", "result": ser.errors})
class BookDeaileAPIView(APIView):
def get(self, request, *args, **kwargs):
book = Book.objects.filter(pk=kwargs.get("pk")).first()
ser = Bookserializers(instance=book, many=True)
return Response({"code": 200, "msg": "查询成功", "result": ser.data})
def put(self, request, *args, **kwargs):
book = Book.objects.filter(pk=kwargs.get("pk")).first()
ser = Bookserializers(instance=book, many=False, data=request.data)
if ser.is_valid():
ser.save()
return Response({"code": 200, "msg": "修改成功", "result": ser.data})
return Response({"code": 200, "msg": "修改败", "result": ser.errors})
def delete(self, request, *args, **kwargs):
Book.objects.filter(pk=kwargs.get("pk")).delete()
return Response({"code": 200, "msg": "删除成功"})
class BookGenericAPIView(GenericAPIView):
queryset = Book.objects.all()
serializer_class = Bookserializers
def get(self, request):
book = self.get_queryset()
ser = self.get_serializer(book, many=True)
return Response({"code": 200, "msg": "查询成功", "result": ser.data})
def post(self, request):
ser = self.get_serializer(data=request.data)
if ser.is_valid():
ser.save()
return Response({"code": 200, "msg": "增加成功", "result": ser.data})
return Response({"code": 200, "msg": "增加失败", "result": ser.errors})
class BookDeleailGenericAPIView(GenericAPIView):
queryset = Book.objects.all()
serializer_class = Bookserializers
def get(self, request, *args, **kwargs):
ser = self.get_serializer(self.get_object(), many=False)
return Response({"code": 200, "msg": "查询成功", "result": ser.data})
def put(self, request, *args, **kwargs):
ser = self.get_serializer(self.get_object(), data=request.data)
if ser.is_valid():
ser.save()
return Response({"code": 200, "msg": "修改成功", "result": ser.data})
return Response({"code": 200, "msg": "修改失败", "result": ser.errors})
def delete(self, request, *args, **kwargs):
self.get_object().delete()
return Response({"code": 200, "msg": "删除成功"})
标签:GenericAPIView,code,ser,get,request,self,APIView,视图,data
From: https://www.cnblogs.com/liyuanxiangls/p/17421503.html