def put(self, request, *args, **kwargs): """ 整体修改单个: 修改一个对象的全部字段 修改对象时,在调用序列化器验证数据时必须指定instance关键字 在调用serializer.save() 底层是通过ModelSerializer内部的update()方法来完成的更新 """ request_data = request.data print("要修改的实例对象 ", request_data) book_id = kwargs.get("id") try: book_obj = Book.objects.get(pk=book_id) except Book.DoesNotExist: return Response({"status": 400, "message": '图书不存在'}) # 更新的时候需要对前端传递的数据进行安全校验 # 更新的时候需要指定关键字参数data # TODO 如果是修改 需要自定关键字参数instance 指定你要修改的实例对象是哪一个 serializer = BookModelSerializerV2(data=request_data, instance=book_obj) serializer.is_valid(raise_exception=True) serializer.save() return Response({ "status": 200, "message": '修改成功', "results": BookModelSerializerV2(book_obj).data })
def put(self, request, *args, **kwargs): # 获得更新的图书的id book_id = kwargs.get('id') # 获取要修改的数据 book_data = request.data print(book_data) if book_id: book_obj = Book.objects.filter(pk=book_id, is_delete=False)[0] if not book_obj: return Response({ "status": 400, "message": '图书不存在' }, status=400) # 使用反序列器进行更新 serializer = BookModelSerializerV2(data=book_data, instance=book_obj) serializer.is_valid(raise_exception=True) obj = serializer.save() return Response( { 'status': 200, 'message': '更新成功', "results": BookModelSerializerV2(obj).data }, status=200) else: return Response({"status": 400, "message": '无id'}, status=400)
def get(self, request, *args, **kwargs): book_id = kwargs.get('id') if book_id: book_obj = Book.objects.filter(pk=book_id, is_delete=False) if book_obj: book_data = BookModelSerializerV2(book_obj[0]).data return Response( { 'status': 200, 'message': '查询单个图书成功', 'results': book_data }, status=200) else: return Response({ 'status': 400, 'message': '查询失败', }, status=400) else: book_obj_all = Book.objects.filter(is_delete=False) book_data = BookModelSerializerV2(book_obj_all, many=True).data return Response( { 'status': 200, 'message': '查询所有成功', 'results': book_data }, status=200)
def post(self, request, *args, **kwargs): """ 增加单个: 传递参数是字典 增加多个: [{},{},{}] 列表中嵌套是一个个的图书对象 :param request: :param args: :param kwargs: :return: """ request_data = request.data if isinstance(request_data, dict): # 代表添加的单个对象 many = False elif isinstance(request_data, list): # 代表添加的是多个对象 many = True else: return Response({ "status": 400, "message": "参数格式有误", }) serializer = BookModelSerializerV2(data=request_data, many=many) serializer.is_valid(raise_exception=True) book_obj = serializer.save() return Response({ "status": 200, "message": "添加图书成功", "results": BookModelSerializerV2(book_obj, many=many).data, })
def get(self, request, *args, **kwargs): book_id = kwargs.get("id") if book_id: book = Book.objects.get(pk=book_id, is_delete=False) data = BookModelSerializerV2(book).data return Response({ "status": 200, "message": "查询单个图书成功", "results": data, }) else: book_objects_all = Book.objects.filter(is_delete=False) book_ser = BookModelSerializerV2(book_objects_all, many=True).data return Response({ "status": 200, "message": "查询单个图书成功", "results": book_ser, })
def patch(self, request, *args, **kwargs): book_id = kwargs.get('id') request_data = request.data if book_id: # 修改单个 book_list = [book_id] book_objs = [request_data] elif not book_id and isinstance(request_data, list): # 修改多个 book_list = [] book_objs = [] for index, i in enumerate(request_data): id = i.pop('id') try: books = Book.objects.get(pk=id) book_list.append(books) book_objs.append(request_data[index]) except Book.DoesNotExist: continue else: return Response({'status': 400, 'message': '参数有误'}) model_serializer = BookModelSerializerV2(data=book_objs, instance=book_list, many=True, partial=True) model_serializer.is_valid(raise_exception=True) model_serializer.save() return Response({'status': 200, 'message': 'ok'})
def post(self, request, *args, **kwargs): book_data = request.data if isinstance(book_data, dict) and book_data != {}: many = False elif isinstance(book_data, list) and book_data != []: many = True else: return Response({ 'status': 400, 'message': '参数格式有误', }, status=400) book_ser = BookModelSerializerV2(data=book_data, many=many) book_ser.is_valid(raise_exception=True) book_obj = book_ser.save() return Response( { 'status': 200, 'message': '新增成功', 'results': BookModelSerializerV2(book_obj, many=many).data }, status=200)
def post(self, request, *args, **kwargs): request_data = request.data if isinstance(request_data, dict): many = False elif isinstance(request_data, list): many = True else: return Response({ "status": 400, "message": "参数格式有误", }) serializer = BookModelSerializerV2(data=request_data, many=many) serializer.is_valid(raise_exception=True) book_obj = serializer.save() return Response({ "status": 200, "message": "添加图书成功", "results": BookModelSerializerV2(book_obj, many=many).data, })
def get(self, request, *args, **kwargs): book_id = kwargs.get("id") if book_id: book = Book.objects.get(pk=book_id) data = BookModelSerializer(book).data print("dan", data) return Response({ "status": 200, "message": "查询单个图书成功", "results": data, }) else: book_objects_all = Book.objects.all() book_ser = BookModelSerializerV2(book_objects_all, many=True).data # print("duo",book_ser) return Response({ "status": 200, "message": "查询所有图书成功", "results": book_ser, })
def patch(self, request, *args, **kwargs): # request_data = request.data # book_id = kwargs.get('id') # # # 修改单个 # if book_id and isinstance(request_data, dict): # book_ids = [book_id] # request_data = [request_data] # # 修改多个 # elif not book_id and isinstance(request_data, list): # book_ids = [] # for dic in request_data: # pk = dic.pop("id",None) # if pk: # book_ids.append(pk) # else: # return Response({ # 'status':400, # 'message':'pk不存在' # },status=400) # else: # return Response({ # 'status': 400, # 'message': '参数有误' # }, status=400) # # # 所有要修改的图书对象 # book_list = [] # new_data = [] # for index,pk in enumerate(book_ids): # try: # book_obj = Book.objects.get(pk=pk) # book_list.append(book_obj) # new_data.append(request_data[index]) # except Exception: # pass # # # 将单个修改转换成群体修改 # book_ser = BookModelSerializerV2(data=new_data,instance=book_list, partial=True, many=True) # book_ser.is_valid(raise_exception=True) # book_ser.save() # return Response({ # 'status': 200, # 'message': 'success' # }, status=200) request_data = request.data book_id = kwargs.get('id') # 如果id存在且传递的request.data格式是字典 单个修改 转换成群体修改一个 if book_id and isinstance(request_data, dict) and request_data != {}: book_ids = [book_id] request_data = [request_data] elif not book_id and isinstance(request_data, list) and request_data != []: book_ids = [] for dic in request_data: pk = dic.pop("id", None) if pk: book_ids.append(pk) else: return Response({ "status": status.HTTP_400_BAD_REQUEST, 'message': "pk不存在" }) else: return Response({ "status": status.HTTP_400_BAD_REQUEST, 'message': "参数格式有误", }) # 进行筛选 book_list = [] new_data = [] for index, pk in enumerate(book_ids): try: book_obj = Book.objects.get(pk=pk) book_list.append(book_obj) new_data.append(request_data[index]) except Book.DoesNotExist: pass book_ser = BookModelSerializerV2(data=new_data, instance=book_list, partial=True, many=True) book_ser.is_valid(raise_exception=True) book_ser.save() return Response({'status': 200, 'message': 'success'})
def patch(self, request, *args, **kwargs): """ 整体修改单个: 修改一个对象的全部字段 修改对象时,在调用序列化器验证数据时必须指定instance关键字 在调用serializer.save() 底层是通过ModelSerializer内部的update()方法来完成的更新 """ # 获取要修改的对象的值 # request_data = request.data # 获取要修改的图书的id # book_id = kwargs.get("id") # try: # book_obj = Book.objects.get(pk=book_id) # except Book.DoesNotExist: # return Response({ # "status": 400, # "message": '图书不存在' # }) # 更新的时候需要对前端传递的数据进行安全校验 # 更新的时候需要指定关键字参数data # TODO 如果是修改 需要自定关键字参数instance 指定你要修改的实例对象是哪一个 # serializer = BookModelSerializerV2(data=request_data, instance=book_obj, partial=True) # serializer.is_valid(raise_exception=True) # 经过序列化器对 全局钩子与局部钩子校验后 开始更新 # serializer.save() # return Response({ # "status": 200, # "message": '修改成功', # "results": BookModelSerializerV2(book_obj).data # }) """ 单个: id 传递的修改的内容 1 {book_name: "python"} 多个: 多个id 多个request.data id: [1,2,3] request.data [{},{},{}] 如何确定要修改的id与值的对应关系 要求前端传递过来的参数按照一定的格式 [{pk:1, book_name: "python"},{pk:2, price:300.1},{pk:3, publish: 3}] """ request_data = request.data book_id = request.query_params.get("id") # 如果id存在且传递的request.data格式是字典 单个修改 转成成群体修改一个 if book_id and isinstance(request_data, dict): book_ids = [book_id] request_data = [request_data] elif not book_id and isinstance(request_data, list): book_ids = [] # 将所有要修改的图书的id取出放入 book_ids中 for dic in request_data: pk = dic.pop("id", None) if pk: book_ids.append(pk) else: return Response({ "status": status.HTTP_400_BAD_REQUEST, "message": "PK不存在", }) else: return Response({ "status": status.HTTP_400_BAD_REQUEST, "message": "参数格式有误", }) print(request_data) print(book_ids) # TODO 需要判断传递过来的id对应的图书是否存在 对book_ids 以及 request_data进行筛选 # TODO 如果id对应的图书不存在 移除id id对应的request_data也需要移除 book_list = [] # 所有要修改的图书对象 new_data = [] # 图书对象对应要修改的值 for index, pk in enumerate(book_ids): # 禁止在循环中对正在循环的列表长度做修改 try: book_obj = Book.objects.get(pk=pk) book_list.append(book_obj) new_data.append(request_data[index]) except Book.DoesNotExist: # 图书对象不存在 则将id与对应的数据移除 # index = book_ids.index(pk) # request_data.pop(index) continue book_ser = BookModelSerializerV2(data=new_data, instance=book_list, partial=True, many=True) book_ser.is_valid(raise_exception=True) book_ser.save() return Response({ "status": status.HTTP_200_OK, "message": "修改成功", })
def patch(self, request, *args, **kwargs): """ 单个: id 传递的修改的内容 1 {book_name: "python"} 多个: 多个id 多个request.data id: [1,2,3] request.data [{},{},{}] 如何确定要修改的id与值的对应关系 要求前端传递过来的参数按照一定的格式 [{pk:1, book_name: "python"},{pk:2, price:300.1},{pk:3, publish: 3}] """ request_data = request.data book_id = kwargs.get("id") # 如果id存在且传递的request.data格式是字典 单个修改 转成成群体修改一个 if book_id and isinstance(request_data, dict): book_ids = [book_id] request_data = [request_data] elif not book_id and isinstance(request_data, list): # 修改多个 book_ids = [] # 将所有要修改的图书的id取出放入 book_ids中 for dic in request_data: pk = dic.pop("id", None) if pk: book_ids.append(pk) else: return Response({ "status": status.HTTP_400_BAD_REQUEST, "message": "PK不存在", }) else: return Response({ "status": status.HTTP_400_BAD_REQUEST, "message": "参数格式有误", }) # print(request_data) # print(book_ids) # TODO 需要判断传递过来的id对应的图书是否存在 对book_ids 以及 request_data进行筛选 # TODO 如果id对应的图书不存在 移除id id对应的request_data也需要移除 book_list = [] # 所有要修改的图书对象 new_data = [] # 图书对象对应要修改的值 for index, pk in enumerate(book_ids): # 禁止在循环中对正在循环的列表长度做修改 try: book_obj = Book.objects.get(pk=pk) book_list.append(book_obj) new_data.append(request_data[index]) except Book.DoesNotExist: # 图书对象不存在 则将id与对应的数据移除 # index = book_ids.index(pk) # request_data.pop(index) continue book_ser = BookModelSerializerV2(data=new_data, instance=book_list, partial=True, many=True) book_ser.is_valid(raise_exception=True) book_ser.save() return Response({ "status": status.HTTP_200_OK, "message": "修改成功", })