rest_framework序列化组件使用——Serializer,rest_framework序列化组件使用——ModelSerializer,rest_framework序列化组件 之 ——局部钩子 全局钩子,rest_framework序列化组件 之 ——数据保存校验功能,图书增删改查 rest_framework 接口
rest_framework序列化组件使用Serializer
注:source 可以指定一个字段名,表模型,还可以指定表模型里的方法,source 指定的如果是方法不用加括号自己执行
1,写一个类继承serializers.Serializer 2,视图层调这个类实例化产生实例化对象 3,注意返回用的是rest_framework 的 Response from rest_framework import serializers class BookSerialize(serializers.Serializer): nid = serializers.CharField() # (1)source的用法1:起别名 # name = serializers.CharField(source="name") # source 指定要序列化的字段,不能写两个name author_name = serializers.CharField(source="name") # 相当于给name字段显示起别名为book_name price = serializers.CharField() # (2)source的用法2:可以指定表模型 # publish = serializers.CharField() # 可以利用__str__ 显示序列化 # publish = serializers.CharField(source="publish.name") # source可以指定表模型 # (3)source的用法3:指定表模型的方法,相当于直接触发序列化表里的方法执行 # xx = serializers.CharField(source="test") # source可以指定表模型的方法,将该返回值的结果赋值给xx 相当于给表模型添加字段 # rest_framework组件之SerializerMethodField 的方法使用,写一个get+字段名的函数 authors = serializers.SerializerMethodField() def get_authors(self, obj): # obj为序列化的对象 author_list = obj.authors.all() ser = AuthorSerialize(author_list, many=True) return ser.data # 返回的结果为序列化打印的对象
视图层: from rest_framework.views import APIView from rest_framework.response import Response from app01.myserialize import BookSerialize class Books(APIView): def get(self, request, *args, **kwargs): response = {"status": 100, "msg": "查看所有"} # 方式1:自己手撸序列化 book_list = models.Book.objects.all() data = [{"title": book.title, "publish_date": book.publishDate} for book in book_list ] return HttpResponse("ok") # 方式2:django原生自带序列化 (不推荐使用) from django.cores.serializes import serialize
books = models.Book.objects.all() data = serialize(books,'json') # django自带的序列化组件 return HttpResponse(data) # 方式3:推荐使用 all_author = Author.objects.all() # 产生序列化的对象 ser = BookSerialize(all_author, many=True) # many=True 表示序列化多条 many=False 表示序列化单条 response["data"] = ser.data # 序列化以后的数据在data里 return Response(response) # 方式4: ret=models.Book.objects.all().values('nid','title') dd=list(ret) return HttpResponse(json.dumps(dd))
rest_framework序列化组件使用ModelSerializer
1,写一个类继承ModelSerializer 2,视图层调这个类实例化产生实例化对象 3,注意返回用的是rest_framework 的 Response from rest_framework import serializers class BookSerialize(serializers.ModelSerializer): # ModelSerializer类下接元信息 class Meta: model = models.Author # fields = ["name",] # 指定序列化哪些字段 fields = '__all__' # 序列化所有字段 一般不用 # exclude = ["name", ] # 排除那些字段不显示,不与查询所有连用 # depth=1 指定查询的深度 publish=serializers.CharField(source='publish.name') # 元信息连表显示的是字段id 所以重写序列化字段
视图层: from rest_framework.views import APIView from rest_framework.response import Response from app01.myserialize import BookSerialize class Books(APIView): def get(self, request, *args, **kwargs): response = {"status": 100, "msg": "查看所有"} all_author = Author.objects.all() # 产生序列化的对象 ser = BookSerialize(all_author, many=True) # many=True 表示序列化多条 response["data"] = ser.data # 序列化以后的数据在data里 return Response(response)
rest_framework序列化组件 之 局部钩子 全局钩子
注:rest_framework 钩子函数源码 从 is_valid 入口
语法: validate + 校验字段名 from rest_framework.exceptions import ValidationError class BookSerialize(serializers.ModelSerializer): class Meta: model = models.Author fields = '__all__' # 序列化所有字段 一般不用 # 局部钩子 写在序列化组件里 def validate_name(self,value): if value.startswith("sb"): raise ValidationError("不能以sb开头") return value # 全局钩子 所有字段校验通过 def validate(self, value): name = value.get("name") price = value.get("price") if name != price: raise ValidationError("书与价格不能比较") return value
rest_framework序列化组件 之 数据保存校验功能
from rest_framework.exceptions import ValidationError class BookSerialize(serializers.ModelSerializer): class Meta: model = models.Author fields = '__all__' # 序列化所有字段 一般不用 # 视图层 from rest_framework.views import APIView class Books(APIView): def post(self, request): # 添加一条数据 print( request.data ) response = {"status": 100, "msg": "插入成功"} try: book_ser = BookSerialize(data=request.data) if book_ser.is_valid(): # 数据校验,查看钩子源码入口 is_valid 进入 book_ser.save() # 修改数据库 response['data'] = book_ser.data else: response['msg'] = book_ser.errors except Exception as e: response['msg'] = str(e) return Response(response)
图书增删改查 rest_framework 接口
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from app01.myserialize import BookSerialize from rest_framework.response import Response from rest_framework.views import APIView class Books(APIView): # get请求 查所有 def get(self, request, *args, **kwargs): response = {"status": 100, "msg": "查看所有"} all_book = Book.objects.all() ser = BookSerialize(all_book, many=True) response["data"] = ser.data # 序列化以后的数据在data里 return Response(response) # post请求 添加数据 def post(self, request): response = {"status": 100, "msg": "插入成功"} try: book_ser = BookSerialize(data=request.data) if book_ser.is_valid(): book_ser.save() response['data'] = book_ser.data else: response['msg'] = book_ser.errors except Exception as e: response['msg'] = str(e) return Response(response) class BookView(APIView): # get请求 查看一条数据 def get(self, request, pk, *args, **kwargs): response = {"status": 100, "msg": "查看单条"} book = Book.objects.filter(nid=pk).first() ser = BookSerialize(book, many=False) response["data"] = ser.data # 序列化以后的数据在data里 return Response(response) # delete请求 删除数据 def delete(self, request, pk, *args, **kwargs): Book.objects.filter(nid=pk).delete() return Response("") # put/patch请求 更新数据 def put(self, request, pk): response = {"status": 100, "msg": "修改成功"} book_obj = Book.objects.filter(nid=pk).first() book_ser = BookSerialize(data=request.data, instance=book_obj) # 反序列化,指定要修改的数据库 if book_ser.is_valid(): book_ser.save() # 修改数据库( rest_framework封装了代码 ) response["data"] = book_ser.data else: response["error"] = book_ser.error_messages return Response(response)