简单的增删查改接口,其中增,改需要进行反序列化和校验:

    1. class GoodsView1(APIView):
    2. authentication_classes = []
    3. permission_classes = []
    4. throttle_classes = [VisitLimit, ]
    5. def get(self,request):
    6. """查所有数据或(如果带有id证明是查一个)"""
    7. id = request.query_params.get('id')
    8. if not id:
    9. goods = Goods.objects.all()
    10. serializer = GoodsSerializer(goods,many=True)
    11. else:
    12. goods_obj = get_object_or_404(Goods,id=id)
    13. serializer = GoodsSerializer(goods_obj)
    14. return Response(serializer.data)
    15. def post(self,request):
    16. """增接口"""
    17. data = request.data
    18. # 只需用data关键字把待反序列化的数据传进去
    19. serializer = GoodsSerializer(data=data)
    20. if serializer.is_valid():
    21. serializer.save()
    22. return Response(serializer.data)
    23. return Response(serializer.errors)
    24. def delete(self,request):
    25. """删接口,查询单个和这个删除以及更新接口我都是?id=1这样传参,可以统一接口url,如果在url传参路由就会要重新定义"""
    26. id = request.query_params.get('id')
    27. if id:
    28. book_obj = get_object_or_404(Goods,id=id)
    29. book_obj.delete()
    30. return Response("删除成功")
    31. return Response("您必须传入待删除的id,不能一次性全删")
    32. def patch(self,request):
    33. """更新接口"""
    34. id = request.query_params.get('id')
    35. if id:
    36. book_obj = get_object_or_404(Goods, id=id)
    37. # instance是待修改的对象,data是修改的内容
    38. serializer = GoodsSerializer(data=request.data, instance=book_obj)
    39. if serializer.is_valid():
    40. serializer.save()
    41. # 更新成功后返回更新的这条记录
    42. return Response(serializer.data)
    43. return Response(serializer.errors)
    44. return Response("您必须传入待更新的id")