简单的增删查改接口,其中增,改需要进行反序列化和校验:
class GoodsView1(APIView):
authentication_classes = []
permission_classes = []
throttle_classes = [VisitLimit, ]
def get(self,request):
"""查所有数据或(如果带有id证明是查一个)"""
id = request.query_params.get('id')
if not id:
goods = Goods.objects.all()
serializer = GoodsSerializer(goods,many=True)
else:
goods_obj = get_object_or_404(Goods,id=id)
serializer = GoodsSerializer(goods_obj)
return Response(serializer.data)
def post(self,request):
"""增接口"""
data = request.data
# 只需用data关键字把待反序列化的数据传进去
serializer = GoodsSerializer(data=data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors)
def delete(self,request):
"""删接口,查询单个和这个删除以及更新接口我都是?id=1这样传参,可以统一接口url,如果在url传参路由就会要重新定义"""
id = request.query_params.get('id')
if id:
book_obj = get_object_or_404(Goods,id=id)
book_obj.delete()
return Response("删除成功")
return Response("您必须传入待删除的id,不能一次性全删")
def patch(self,request):
"""更新接口"""
id = request.query_params.get('id')
if id:
book_obj = get_object_or_404(Goods, id=id)
# instance是待修改的对象,data是修改的内容
serializer = GoodsSerializer(data=request.data, instance=book_obj)
if serializer.is_valid():
serializer.save()
# 更新成功后返回更新的这条记录
return Response(serializer.data)
return Response(serializer.errors)
return Response("您必须传入待更新的id")