put请求
接口:urlpatterns = [
url(r'^v2/book/$', views.Bookv2.as_view()),
url(r'^v2/book/(?P<pk>.*)/$', views.Bookv2.as_view()),
]
单整体改一般用put
参数:
如果partial值设置为True,就是可以局部改
1)单整体修改,一般用put请求:
V2BookModelSerializer(
instance=要被更新的对象,
data=用来更新的数据,
partial=默认False,必须的字段全部参与校验
)
实现:单整体修改
# 单整体改 :对 v2/book/(pk)/访问要把pk传入,然后instance=修改的对象
# Bookv2ModelSerializer(instance=修改的对象, data=request_data,partial=默认False)
def put(self, request, *args, **kwargs):
request_data = request.data
pk = kwargs.get('pk')
old_book_obj = models.Book.objects.filter(pk=pk).first() # 获取obj
# 目的:将众多数据的校验交给序列化来处理,让序列化类进行反序列化操作,校验成功后入库
# data传入数据是进行校验,并且才能走.is_valid(raise_exception=True)校验是否成功
# instance如若有值,save走的是update操作,进行修改操作
book_ser = serializers.Bookv2ModelSerializer(instance=old_book_obj, data=request_data)
book_ser.is_valid(raise_exception=True) # raise_exception=True如果问题抛出异常
book_ser.save()
return Response({
'status': 0,
'msg': '修改成功',
"results": book_ser.data
})
patch请求:
接口:urlpatterns = [
url(r'^v2/book/$', views.Bookv2.as_view()),
url(r'^v2/book/(?P<pk>.*)/$', views.Bookv2.as_view()),
]
参数:
单局部修改,一般用patch请求:
V2BookModelSerializer(
instance=要被更新的对象,
data=用来更新的数据,
partial=设置True,必须的字段都变为选填字段)
注:partial设置True的本质就是使字段 required=True 校验规则失效
# 单局部改 :只需要在序列化类参数加上partial=True,就能进行局部修改
# Bookv2ModelSerializer(instance=old_book_obj, data=request_data,partial=True)
def patch(self, request, *args, **kwargs):
request_data = request.data
pk = kwargs.get('pk')
old_book_obj = models.Book.objects.filter(pk=pk).first()
# partial=True
book_ser = serializers.Bookv2ModelSerializer(instance=old_book_obj, data=request_data,partial=True)
book_ser.is_valid(raise_exception=True)
book_ser.save()
return Response({
'status': 0,
'msg': '修改成功',
"results":serializers.Bookv2ModelSerializer(old_book_obj).data
})
# 群局部改(单局部改):请求数据 -[{pk:1,name=123},{pk:2,name=456},{pk:8,price:666}]
def patch(self, request, *args, **kwargs):
request_data = request.data
pk = kwargs.get('pk')
if pk and isinstance(request_data, dict): # 单改
pks = [pk, ]
request_data = [request_data, ]
elif isinstance(request_data, list): # 群改
pks = []
for dic in request_data:
# 字典是可变类型,在弹出的时候,原生的字典也会改变,dic的指向依然是request_data内存地址,dic变,它也变
pk = dic.pop('pk', None)
if pk:
pks.append(pk) # 把pk值弹出来,加入pks
else:
return Response({
'status': 2,
'msg': '数据有误',
})
else:
return Response({
'status': 1,
'msg': '数据有误',
})
# pks与request_data数据筛选
# 1.将pks中的没有对应数据的pk与数据已删除的数据pk移除,request_data索引对应的数据也移除
# 2.将合理的pks转换为对象
obj_list = []
new_request_data = []
for index, pk in enumerate(pks):
try:
# pk对应的数据合理,将合理的对象存储,并把删除的数据过滤掉
obj = models.Book.objects.get(pk=pk,is_delete=False)
obj_list.append(obj)
# 对应索引的数据就需要保存下来
new_request_data.append(request_data[index])
except:
# pk对应的数据有误,将对应索引的data从request_data中移除
# request_data.pop(index)
continue
book_ser = serializers.Bookv2ModelSerializer(instance=obj_list, data=new_request_data, partial=True, many=True)
book_ser.is_valid(raise_exception=True)
book_objs = book_ser.save()
return Response({
'status': 0,
'msg': '修改成功',
"results": serializers.Bookv2ModelSerializer(book_objs, many=True).data
})
# 群改
# 重点:ModelSerializer与ListSerializer建立关联的是:
# 在ModelSerializer类的 Meta:list_serializer_class = Bookv2ListSerializer建立联系
class Bookv2ListSerializer(ListSerializer):
def update(self, instance, validated_data):
print(instance) # book对应各个对象
print(validated_data) # 修改的数据
print(self.child) # 服务模型序列化的类
for index, obj in enumerate(instance):
self.child.update(obj, validated_data[index])
return instance
序列化类
# 整合序列化和反序列化
class Bookv2ModelSerializer(ModelSerializer):
# publishs = PublishModelSerializer()
class Meta:
model = models.Book
fields = ('name', 'price', 'img', 'publish_name', 'author_list', 'publish', 'authors')
# 群改,需要设置 自定义ListSerializer,重写update方法
list_serializer_class = Bookv2ListSerializer