python全栈开发day99-DRF序列化组件

1.解释器组件源码分析

https://www.processon.com/view/link/5ba0a8e7e4b0534c9be0c968

2.基于CBV的接口设计

  1)、django循环queryset对象构造数组套字典方式

  2)、django.serializers.serialize方式

  3)、restframework序列化组件方式

  

###################### 基于CBV的接口设计#######################

# class CourseView(View):
#
# def get(self,request):
#
# course_list=Course.objects.all()
# ret=[]
# for course in course_list:
# ret.append({
# "title":course.title,
# "desc":course.desc,
# })
#
#
# return HttpResponse(json.dumps(ret,ensure_ascii=False)) ###################### 基于DRF的接口设计####################### # from rest_framework.views import APIView
# from rest_framework.response import Response
# from rest_framework.parsers import JSONParser,FormParser,FileUploadParser
# from app01.models import Course
# #
#
# from rest_framework import serializers
# class CourseSerializer(serializers.Serializer):
# title=serializers.CharField(max_length=32)
# desc=serializers.CharField(max_length=32)
#
#
# class CourseView(APIView):
#
# def get(self,request):
# '''
# 查看所有数据
# 方式1:
# ret=[]
# for course in course_list:
# ret.append({
# "title":course.title,
# "desc":course.desc,
# })
#
# json.dumps(ret,ensure_ascii=False)
#
# 方式2:
# from django.core.serializers import serialize # Django的序列化组件
# data=serialize("json",course_list)
# print("data",data)
#
# 方式3:
# restframework序列化组件
# :param request:
# :return:
# '''
#
# course_list=Course.objects.all()
#
# cs=CourseSerializer(course_list,many=True)
# print("====>",cs.data) # 序列化接口
#
# '''
#
# [OrderedDict([('title', 'python'), ('desc', 'python非常好')]), OrderedDict([('title', 'linux'), ('desc', 'linux好')]), OrderedDict([('title', 'go'), ('desc', 'gogogo')])]
#
# '''
#
# return Response(cs.data)
#
#
# def post(self,request):
#
# print(request.data) # 静态方法:解析数据工作
# cs=CourseSerializer(data=request.data)
# if cs.is_valid(): # 校验
#
# # Course.objects.create(**request.data)
#
# return Response(cs.data) # 序列化数据
# else:
# return Response(cs.errors) # 序列化错误信息
# ##########################################################################

基于CBV的接口设计

3.restframework序列化组件

  1.serializers.Serializer    

class BookSerializer(serializers.Serializer):
title = serializers.CharField()
price = serializers.IntegerField()
# publish_email = serializers.CharField(source='publish.email')
# publish_name = serializers.CharField(source='publish.name')
publish = serializers.CharField(source='publish.nid')
authors = serializers.SerializerMethodField() def get_authors(self, obj):
data = []
print(obj.authors.all())
for i in obj.authors.all():
temp = []
temp.append(i.name)
temp.append(i.email)
data.append(temp)
return data

  2.serializers.ModelSerializer

class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = "__all__"
# exclude = ["publish"] # publish = serializers.CharField(source='publish.nid')
# authors = serializers.SerializerMethodField()
#
# def get_authors(self, obj):
# data = []
# print(obj.authors.all())
# for i in obj.authors.all():
# temp = []
# temp.append(i.name)
# temp.append(i.email)
# data.append(temp)
# return data class BookView(APIView):
# parser_classes = [FormParser, JSONParser, MultiPartParser] def get(self, request):
book_list = Book.objects.all()
bs = BookSerializer(book_list, many=True)
return response.Response(bs.data) def post(self, request):
serializer = BookSerializer(data=request.data) if serializer.is_valid(): serializer.save()
print(serializer.data) # 必须在save()方法之后
# {'id': 8, 'title': '第10本书', 'price': 12, 'publish': 1, 'authors': [1, 3]}
print(serializer.validated_data)
# OrderedDict([('title', '第10本书'), ('price', 12), ('publish', < Publish: 沙河出版社 >),
# ('authors', [ < Author: 下马哥 >, < Author: eva >])])
return response.Response(serializer.data)
else:
return response.Response(serializer.errors)
上一篇:iOS开发项目之MVC与MVVM


下一篇:压缩Sqlite数据文件大小,解决数据删除后占用空间不变的问题