https://www.bilibili.com/video/BV1z5411D7BQ?p=11&vd_source=caabcbd2a759a67e2a3de8acbaaf08ea
views.py
class BooketailView(APIView):
def get(self,request,id):
book =Book.objects.get(pk=id)
# 序列化传参instance,反序列化传参data
serializer=BookSerializers(instance=book,many=False)
return Response(serializer.data)
def put(self,request,id):
# 获取提交的更新数据
print(f"提交的数据:{request.data}")
update_book=Book.objects.get(pk=id)
#构建序列化器对象 # instance放原来的信息,data放要修改成的信息
# serializer.data是拿instance传的参数做序列化,
# 所以要加下面serializer.instance=Book.objects.get(pk=id)
# 赋值最新的数据到instance,serializer.data返回的才是更新的信息
# 个人认为下面不加instance就可以了,一样能返回更新的数据,但是没有展示id
serializer = BookSerializers(instance=update_book,data=request.data, many=False)
if serializer.is_valid(): #数据验证 ,抛出异常,代码不会往下执行 使用serializer.is_valid(raise_exception=True)
# 更新逻辑
Book.objects.filter(pk=id).update(**serializer.validated_data)
# 重新赋值instance
serializer.instance=Book.objects.get(pk=id)
return Response(f"更新成功{serializer.data}")
else:
return Response(f"更新失败: {serializer.errors}")
def delete(self,request,id):
Book.objects.get(pk=id).delete()
return Response("删除成功")