def put(self, req, book_id): data_dict = req.data book = BookInfo.objects.get(id=book_id) ser = BookInfoSerializer(instance=book, data=data_dict) ser.is_valid(raise_exception=True) ser.save() return Response(ser.data, status=status.HTTP_201_CREATED)
def post(self, request): # 1、获取参数 data_dict = request.data # 2、创建序列化器 ser = BookInfoSerializer(data=data_dict) # 3、校验、数据入库 ser.is_valid(raise_exception=True) ser.save() # 4、返回响应 return Response(ser.data, status=status.HTTP_201_CREATED)
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)
def post(self, request): # 1、获取参数 dict_data = json.loads(request.body.decode()) btitle = dict_data.get('btitle') bpub_date = dict_data.get('bpub_date') bread = dict_data.get('bread') bcomment = dict_data.get('bcomment') # 2、校验参数 ser = BookInfoSerializer(data=dict_data) try: ser.is_valid(raise_exception=True) except ValidationError as error: return http.JsonResponse({ 'code': 405, 'msg': next(iter(error.detail.values()))[0].title() }) # 3、数据入库 # book = BookInfo.objects.create(**dict_data) book = ser.save() # 4、返回响应 return http.JsonResponse(book, status=201)
def deserializer(request): # 模拟前端提交的数据 # data = {"id":1, "btitle": "西游记之Django开发", "bpub_date": "2000-01-01", "is_delete": 1, "bread": 100, "bcomment": 10} # data = {"hname": "猪八戒", "hbook": 100} data = {"btitle": "水浒传之Django开发5", "bpub_date": "2000-01-01"} # 查询数据库, 得到一个bookInfo模型对象, 用于进行更新 book = BookInfo.query.get(pk=5) # s = BookInfoSerializer(book, data=data) s = BookInfoSerializer(data=data) # s = HeroInfoSerializer(data=data) # 判断前端数据是否合法, True表示合法 print(s.is_valid(raise_exception=True)) # 可以输出错误信息 print(s.errors) # 可以提取处校验结束之后的干净数据 print(s.validated_data) s.save() return HttpResponse("反序列化结束! %s" % s.validated_data)
# 获取一本书 book = BookInfo.objects.get(id=9) # 准备数据 req_data = { 'btitle': 'django_rest', 'bpub_date': '2019-06-01', 'bread': 21, 'bcomment': 20 } # 创建序列化器对象 serializer = BookInfoSerializer(book, data=req_data) # 数据校验 serializer.is_valid() # 数据保存:此处save会调用序列化器类中的create方法 serializer.save() # 获取create方法返回的对象序列化之后的数据 res = serializer.data res = json.dumps(res, indent=1, ensure_ascii=False) print(res) # # 查询获取图书对象 # book = BookInfo.objects.all() # # # 创建序列化对象 # serializer = BookInfoSerializer(book,many=True) #
# 关联对象嵌套序列化!! hero = HeroInfo.objects.get(id=1) serializer_hero = HeroInfoSerializer(instance=hero) serializer_hero.data """反序列化""" # 新建 data = { 'btitle': 'django三国演义', 'bpub_date': '1996-5-1', 'bcomment': 10, 'bread': 30 } serializer = BookInfoSerializer( data=data) # 新建 没有参数instance,看重写的create方法 只传入一个参数 # serializer.is_valid() # 返回布尔值 serializer.is_valid(raise_exception=True) # 如果出现异常自动抛出 # serializer.errors # is_valid 返回 False,看错误信息 # serializer.validated_data # OrderedDict([('btitle', '三国演义'), ('bpub_date', datetime.date(1996, 5, 1))]) serializer.save() # 执行继承的方法 实质 选择方法(update/create 方法里保存到数据库) # 更新 book = BookInfo.objects.get(id=9) data = { 'btitle': '大国django三国演义', 'bpub_date': '1996-6-6', 'bcomment': 10, 'bread': 30 } serializer = BookInfoSerializer(instance=book, data=data) serializer.is_valid(raise_exception=True) serializer.save() # 序列化中的saexitve实质 依靠方法模型自身的save()
import os if not os.environ.get('DJANGO_SETTINGS_MODULE'): os.environ.setdefault("DJANGO_SETTINGS_MODULE", "drf.settings") # 让Django环境进行一次初始化 import django django.setup() import json from booktest.models import BookInfo,HeroInfo from booktest.serializers import HeroInfoSerializer,BookInfoSerializer if __name__ == "__main__": # 获取id为1的图书 book = BookInfo.objects.get(id=1) # 准备数据 data = {'btitle': '射雕英雄传-2', 'bpub_date': '2000-01-01'} # 创建序列化器对象 serializer = BookInfoSerializer(book, data=data) # 反序列化-数据校验 res = serializer.is_valid() print(res) # 反序列化-数据保存(调用序列化器类中update) serializer.save() # 获取更新对象序列化之后的数据 print(serializer.data)
print(serializer.data) """ 4、反序列化,书籍对象 """ from booktest.serializers import BookInfoSerializer # 1、准备数据 book_dict = { "btitle": "活着", "bpub_date": "2020-1-01", "bread": "50", "bcomment": "20", } # 2、创建序列化器 serializer = BookInfoSerializer(data=book_dict) # serializer.is_valid() serializer.is_valid(raise_exception=True) # 3、输出 print(serializer.data) """ 5、反序列化创建对象入库 """ from booktest.serializers import BookInfoSerializer # 1、准备数据 book_dict = { "btitle": "活着", "bpub_date": "2020-1-01", "bread": "50", "bcomment": "20", } # 2、创建序列化器 serializer = BookInfoSerializer(data=book_dict)