Django serializer优化类视图 Django serializer优化类视图的实现示例
慢跑的曾四九 人气:0一. create优化
在serializer序列化中,我们通过创建序列化器对象的方式地简化了视图函数的代码,前端传入的数据通过反序列化操作进行了各种数据校验,代码如下:
from django.http import JsonResponse from django.views import View import json from .models import Project from .serializers import ProjectsSerializer class ProjectsPage(View): ''' 类视图 ''' def post(self, request): input_data = json.loads(request.body) serializer_obj = ProjectsSerializer(data=input_data) if not serializer_obj.is_valid(): return JsonResponse({"code": 1, "res": "error", "msg": serializer_obj.errors}) obj = Project.objects.create(**input_data) ser_obj = ProjectsSerializer(instance=obj) return JsonResponse(ser_obj.data, status=201)
可以看到,这里创建了两个序列化器类对象,一个serializer_obj用于反序列化参数校验(用data接受前端参数),一个ser_obj用于序列化输出(用instance接受模型类对象),其实可以去掉ser_obj,然后调用serializer_obj的save()方法,save()方法会自动调用序列化器类对象中定义的create方法
def post(self, request): """ post请求,新增数据 :param request: :return: """ try: data = json.loads(request.body, encoding='utf-8') except Exception as e: result = { "msg": "参数有误", "code": 0 } return JsonResponse(result, status=400) ser_obj = ProjectsSerializer(data=data) try: ser_obj.is_valid(raise_exception=True) except Exception as e: result = {"msg": "参数有误"} result.update(ser_obj.errors) return JsonResponse(result, status=400) ser_obj.save() resp = {"msg": "创建成功"} resp.update(ser_obj.data) return JsonResponse(resp, status=201)
序列化器类中的create方法需要提前定义,该方法是父类的create方法,我们可以进行重写,父类方法源码如下:
def create(self, validated_data): return [ self.child.create(attrs) for attrs in validated_data ]
重写父类的create方法,并返回模型类对象
def create(self, validated_data): obj = Project.objects.create(**validated_data) return obj
使用postman验证结果:
写入数据库的数据:
二. update优化
def put(self, request, pk): try: obj = Project.objects.get(id=pk) except Exception as e: result = { "msg": "参数有误", "code": 0 } return JsonResponse(result, status=400) update_data = json.loads(request.body) serializer_obj = ProjectsSerializer(data=update_data) if not serializer_obj.is_valid(): return JsonResponse({"code": 1, "res": "error", "msg": serializer_obj.errors}) obj.name = serializer_obj.validated_data.get('name') or obj.name obj.leader = serializer_obj.validated_data.get('leader') or obj.leader obj.desc = serializer_obj.validated_data.get('desc') or obj.programmer obj.tester = serializer_obj.validated_data.get('tester') or obj.tester obj.save() ser_obj = ProjectsSerializer(instance=obj) return JsonResponse(ser_obj.data, status=201)
上面创建了两个序列化器类的对象,可以进行合并,合并方式跟create方法有点差别,这里是给序列化器对象同时传入data和instance,然后调用save()方法,它会自动去调用序列化器类中的update方法
优化后的put方法
def put(self, request, pk): try: obj = Project.objects.get(id=pk) except Exception as e: result = { "msg": "参数有误", "code": 0 } return JsonResponse(result, status=400) request_data = request.body try: python_data = json.loads(request_data) except Exception as e: result = { "msg": "参数有误", "code": 0 } return JsonResponse(result, status=400) serializer_obj = ProjectsSerializer(instance=obj, data=python_data) try: serializer_obj.is_valid(raise_exception=True) except Exception as e: resp = {'msg': '参数有误'} resp.update(serializer_obj.errors) return JsonResponse(resp, status=400) serializer_obj.save() resp = {'msg': '修改成功'} resp.update(serializer_obj.data) return JsonResponse(resp, status=201)
序列化器类中的update方法需要提前定义,该方法是父类的update方法,我们可以进行重写,父类方法源码如下:
def update(self, instance, validated_data): raise_errors_on_nested_writes('update', self, validated_data) info = model_meta.get_field_info(instance) m2m_fields = [] for attr, value in validated_data.items(): if attr in info.relations and info.relations[attr].to_many: m2m_fields.append((attr, value)) else: setattr(instance, attr, value) instance.save() for attr, value in m2m_fields: field = getattr(instance, attr) field.set(value) return instance
在序列化器类中重写父类的updata方法,并返回模型类对象
def update(self, instance, validated_data): """ 更新数据 :param instance: 待更新的模型类对象 :param validated_data: 校验通过之后的数据 :return: 模型类对象 """ instance.name = validated_data.get('name') or instance.name instance.leader = validated_data.get('leader') or instance.leader instance.tester = validated_data.get('tester') or instance.tester instance.desc = validated_data.get('desc') or instance.desc instance.save() return instance
使用post满验证结果:
友情提示:在调用序列化器类对象的save()方法时,可以以关键字的方式传参,它会自动添加到create方法的validated_data中,应用场景:判断当前项目是哪个用户创建的
加载全部内容