DRF-序列化组件
知识补充
1 django有自己的序列化组件
class LoginView(APIView): parser_classes = [JSONParser] def get(self,request): course_list = Course.objects.all() from django.core.serializers import serialize print(course_list) data = serialize("json",course_list) print('get') print(data) print(type(data)) return render(request,'login.html')
2 序列化组件可以参考form组件和modelform组件
3 序列化组件的校验功能:serializer.is_valid()
4 序列化组件展示错误信息:serializer.errors
普通版
from django.shortcuts import render,HttpResponse from django.views import View # Create your views here. # 导入djangorestframework # 当前访问视图类下设置解析方式 from rest_framework.parsers import JSONParser from rest_framework.views import APIView from app01.models import * from rest_framework import serializers from rest_framework.response import Response class BookSerializer(serializers.Serializer):
# 普通字段 title = serializers.CharField(max_length=32) price = serializers.DecimalField(max_digits=5,decimal_places=2) # 一对多字段 publish_email = serializers.CharField(max_length=32,source="publish.email") publish_name = serializers.CharField(max_length=32,source="publish.name") # 多对多字段 # authors = serializers.CharField(max_length=32,source='authors.all') authors = serializers.SerializerMethodField() def get_authors(self,obj): ret=[] for i in obj.authors.all(): ret.append(i.name) return ret class LoginView(APIView): parser_classes = [JSONParser] def get(self,request): book_list = Book.objects.all() serializer = BookSerializer(book_list,many=True) return Response(serializer.data) # return render(request,'login.html') def post(self,request): print('body',request.body) print(request.data) print('data',request.data) # print('POST', request.POST) return HttpResponse('OK')
注:普通版的保存数据不能使用 serializer.save()
ModelSerializer
class BookSerializer(serializers.ModelSerializer): class Meta: model=Book # fields=["title","price"] fields="__all__" # publish=serializers.CharField(max_length=32,source="publish.name") # # authors=serializers.SerializerMethodField() # def get_authors(self,obj): # ret=[] # for i in obj.authors.all(): # ret.append({"name":i.name,"pk":i.pk}) # return ret class BookView(APIView): def get(self,request): book_list=Book.objects.all() serializer=BookSerializer(book_list,many=True) return Response(serializer.data) def post(self,request): serializer=BookSerializer(data=request.data,many=False) if serializer.is_valid(): serializer.save() # create操作 return Response(serializer.data) else: return Response(serializer.errors)