序列化器:将复杂数据 (如查询集和模型实例) 转换为可以轻松渲染成json等格式 示例:项目信息获取 如下为常规处理方法
def get(self, request):
queryset = Projects.objects.all()
b.将项目的查询集数据转化为嵌套字典的列表
project_list = []
for item in queryset:
item: Projects
project_list.append({
'id': item.id,
'name': item.name,
'leader': item.leader
})
return JsonResponse(project_list, safe=False)
用序列化器实现,如下:
from .serializers import ProjectSerilizer
def get(self, request):
queryset = Projects.objects.all()
serializer = ProjectSerilizer(instance=queryset, many=True)
return JsonResponse(serializer.data, safe=False)
返序列化器:将json等数据转成复杂数据 (如查询集和模型实例) 示例:创建项目,接受前端传值 如下为常规处理方法:
def post(self, request):
try:
python_data = json.loads(request.body)
except Exception as e:
return JsonResponse({'msg': '参数有误'}, status=400)
project_obj = Projects.objects.create(**python_data)
python_dict = {
'id': project_obj.id,
'name': project_obj.name,
'msg': '创建成功'
}
return JsonResponse(python_dict, status=201)
下面用反序列化器实现
from .serializers import ProjectSerilizer
try:
python_data = json.loads(request.body)
except Exception as e:
return JsonResponse({'msg': '参数有误'}, status=400)
serializer11 = ProjectSerilizer(data=python_data)
if not serializer11.is_valid():
return JsonResponse(serializer11.errors, status=400)
serializer = ProjectSerilizer(instance=project_obj)
return JsonResponse(serializer.data, status=201)
|