View optimization of DRF framework serializer

1, create optimization

In serializer serialization, we greatly simplify the code of view functions by creating serializer objects. The data passed in from the front end is verified through deserialization. The code is as follows:

from django.http import JsonResponse
from django.views import View
from django.db import connection
import json
from .models import Projects
from .serializers import ProjectSerializer


class ProjectsPage(View):
    '''
    Class view
    '''
    def post(self, request):

        input_data = json.loads(request.body)

        serializer_check_obj = ProjectSerializer(data=input_data)

        if not serializer_check_obj.is_valid():
            return JsonResponse({"code": 1, "res": "error", "msg": serializer_check_obj.errors})

        obj = Projects.objects.create(**serializer_check_obj.validated_data)

        serializer_obj = ProjectSerializer(instance=obj)
     return JsonResponse(serializer_obj.data, status=201)

As we can see above, we actually created two serializer class objects, a serializer_check_obj is used to deserialize parameter verification (pass parameters to data), a serializer_obj is used to serialize output (pass parameters to instance). Can you create only one serializer object to realize the functions of two objects? The answer is yes, we can remove the serializer_obj, and then call serializer_ Check_ The save() method of obj will automatically call the Create method defined in the model class object

    def post(self, request):

        input_data = json.loads(request.body)

        serializer_check_obj = ProjectSerializer(data=input_data)

        if not serializer_check_obj.is_valid():
            return JsonResponse({"code": 1, "res": "error", "msg": serializer_check_obj.errors})

        serializer_check_obj.save()

        return JsonResponse(serializer_check_obj.validated_data, status=201)

The create method in the model class needs to be defined in advance. This method is the create method of the parent class, and we can rewrite it. The source code of the parent class method is as follows:

 

Override the create method of the parent class in the serializer class and return the model class object

    def create(self, validated_data):
        obj = Projects.objects.create(**validated_data)
        return obj

Verification results:

When calling the save() method of the serializer class object, you can also pass parameters. The passed parameters are passed in the form of keywords, which will be automatically added to the validated of the create method_ In data, we can make some associations based on this parameter, such as judging whether the current project has been logged in or which user created the current project

2, update optimization

The original code is as follows:

    def put(self, request, pk=None):
        if pk:
            update_data = json.loads(request.body)
            obj = Projects.objects.get(id=pk)

            serializer_check_obj = ProjectSerializer(data=update_data)
            if not serializer_check_obj.is_valid():
                return JsonResponse({"code": 1, "res": "error", "msg": serializer_check_obj.errors})

            obj.name = serializer_check_obj.validated_data.get('name') or obj.name
            obj.leader = serializer_check_obj.validated_data.get('leader') or obj.leader
            obj.programmer = serializer_check_obj.validated_data.get('programmer') or obj.programmer
            obj.tester = serializer_check_obj.validated_data.get('tester') or obj.tester
            obj.save()

            serializer_obj = ProjectSerializer(instance=obj)

            return JsonResponse(serializer_obj.data, status=201)

Two serializer class objects are created above. We can also merge them. The merging method is a little different from create. Here, we pass data and instance to the model class object at the same time, and then call the save() method. It will automatically call the update method in the serializer class

Optimized put method:

    def put(self, request, pk=None):
        if pk:
            update_data = json.loads(request.body)
            obj = Projects.objects.get(id=pk)

            serializer_obj = ProjectSerializer(data=update_data, instance=obj)
            if not serializer_obj.is_valid():
                return JsonResponse({"code": 1, "res": "error", "msg": serializer_obj.errors})

            serializer_obj.save()

            return JsonResponse(serializer_obj.data, status=201)

The update method in the model class needs to be defined in advance. This method is the update method of the parent class, which we can rewrite. The source code of the parent method is as follows:

Override the update method of the parent class in the serializer class and return the model class object

    def update(self, instance, validated_data):
        # instance Model class object to be updated
        # validated_data The parameter is the data after verification
        # The model class object that was successfully updated must be returned
        instance.name = validated_data.get('name') or instance.name
        instance.leader = validated_data.get('leader') or instance.leader
        instance.programmer = validated_data.get('programmer') or instance.programmer
        instance.tester = validated_data.get('tester') or instance.tester
        instance.save()
        return instance

Verification results:

Tags: Django

Posted by ssmK on Wed, 01 Jun 2022 04:45:05 +0530