def put(self, request, pk): # 1、获取参数 dict_data = json.loads(request.body.decode()) # 2、校验参数 book = BookInfo.objects.get(pk=pk) origin_data = BookInfoSerializer(instance=book).data origin_data.update(**dict_data) serializer = BookInfoSerializer(instance=book, data=origin_data, partial=True) try: serializer.is_valid(raise_exception=True) except ValidationError as e: return http.JsonResponse({ 'code': 405, 'msg': next(iter(e.detail.values()))[0].title() }) # 3、数据入库 serializer.save() # 4、返回响应 return http.JsonResponse(serializer.data)
serializer.is_valid(raise_exception=True) # 3、入库,会调用序列化器中的create方法 serializer.save() """ 6、反序列化更新对象 """ from booktest.serializers import BookInfoSerializer from booktest.models import BookInfo # 1、准备数据 book_dict = { "bread": "5", } # 2、创建序列化器 book = BookInfo.objects.get(pk=6) origin_data = BookInfoSerializer(instance=book).data origin_data.update(**book_dict) serializer = BookInfoSerializer(instance=book, data=origin_data, partial=True) serializer.is_valid(raise_exception=True) # 3、入库,会调用序列化器中的update方法 serializer.save() '''*****************使用ModelSerializer,进行序列化**********************''' from booktest.serializers import BookInfoModelSerializer from booktest.models import BookInfo book = BookInfo.objects.get(pk=7) serializer = BookInfoModelSerializer(instance=book) serializer.data # {'id': 7, 'btitle': '活着', 'bpub_date': '2019-05-01', 'bread': 30, 'bcomment': 10, 'is_delete': False} '''*****************使用ModelSerializer,进行反序列化**********************''' from booktest.serializers import BookInfoModelSerializer book_dict = { "btitle": "平凡的世界", "bpub_date": "2020-1-01",