4. DRF serializer create method and update method

Previous chapter:

2. Django REST Framework (DRF) Serialization & amp; Deserialization & amp; Data Validation

next chapter:

Five, DRF model serializer ModelSerializer

1. Background

1. Create a request, post, and the user can directly create a piece of data by inputting json data

2. The update request, put, requires two types of data:

  1. The json data passed in by the user, which fields need to be updated.
  2. You need to go to the library to take out the instance that needs to be updated, and then update it.

Our current post creates and puts update requests. They are all database operations performed using the ORM framework in the views.py view function.

create request, post

 # create class
    def post(self, request):
        # 1. Get the json parameter and convert it to the data type (dictionary) in python
        try:
            dic_data = json. loads(request. body)
        except Exception as e:
            return JsonResponse({'msg': 'The parameter is wrong'}, status=400)
        # Get the deserialized instance object
        class_obj = ClassSerializer(data=dic_data)
        # Validate the data
        # Validation failed
        if not class_obj.is_valid():
            return JsonResponse(class_obj. errors, status=400)
        # Create data, execute saql
        miaoclass = MiaoClass.objects.create(**class_obj.validated_data)

        # Perform data echo (serialization) on the created data
        serializer = ClassSerializer(instance=miaoclass)
        return JsonResponse(serializer.data, status=201)

Update request, put:

 def put(self, request, pk):
        # 1. It is necessary to verify whether pk exists in the database
        # 2. Read project data from the database
        try:
            student_obj = MiaoStudent.objects.get(id=pk)
        except Exception as e:
            return JsonResponse({'msg': 'The parameter is wrong'}, status=400)

        # 3. Get the json parameter and convert it into a dictionary
        try:
            dic = json.loads(request.body)
        except Exception as e:
            return JsonResponse({'msg': 'The parameter is wrong'}, status=400)

        # 4. Serialization, converting the dictionary entered by the user into a serialized instance
        serializer_obj=StudentSerializer(data=dic)
        # 5. The serializer verifies the parameters passed in by the user
        # is_valid() data validation
        # serializer_obj.errors error message after verification
        if not serializer_obj.is_valid():
            return JsonResponse(serializer_obj. errors, status=400)

        # 6. Update data and operate the database
        student_obj.sname = serializer_obj.validated_data.get('sname')
        student_obj.sgender = serializer_obj.validated_data.get('sgender')
        student_obj.sid = serializer_obj.validated_data.get('sid')
        student_obj.sscore = serializer_obj.validated_data.get('sscore')
        student_obj.classid_id = serializer_obj.validated_data.get('classid_id')
        student_obj. save()

        # 7. Data display (not required). Convert the read item data into a dictionary
        serializer = StudentSerializer(instance=student_obj)
        return JsonResponse(serializer.data, status=201)

2. Serializer create method and update method

The above processing database operation is carried out in the views view function, now

Encapsulate the behavior of operating the database into the serializer class.

The post create creation operation is implemented through the serializer create method

The put update update operation is implemented through the serializer update method.

2.1 Serializer create method

Original post creation request

class StudentsView(View):

    # query all data
    def get(self, request):
        # get list data
        queryset = MiaoStudent. objects. all()
        print(queryset)
        serializer = StudentSerializer(instance=queryset, many=True)
        return JsonResponse(serializer. data, safe=False)

    # create data
    def post(self, request):
        # 1. Get the json parameter and convert it to the data type (dictionary) in python
        try:
            dic_data = json. loads(request. body)
        except Exception as e:
            return JsonResponse({'msg': 'The parameter is wrong'}, status=400)
        # Get the deserialized instance object
        student_serializer_obj = StudentSerializer(data=dic_data)
        # Validate the data
        # Validation failed
        if not student_serializer_obj.is_valid():
            return JsonResponse(student_serializer_obj. errors, status=400)
        # create data, execute saql
        student=MiaoStudent.objects.create(**student_serializer_obj.validated_data)

        # Perform data echo (serialization) on the created data
        serializer = StudentSerializer(instance=student)
        return JsonResponse(serializer.data, status=201)

1. Change the original code to create data

# create data, execute saql
        student=MiaoStudent.objects.create(**student_serializer_obj.validated_data)

replace with

 # create data, execute saql
        # student=MiaoStudent.objects.create(**student_serializer_obj.validated_data)
        # Operate the database through the serializer
        student_serializer_obj. save()
        # Perform data echo (serialization) on the created data
        #serializer = StudentSerializer(instance=student)
        return JsonResponse(student_serializer_obj.data, status=201)

When constructing the serializer object, only pass in the data= parameter.

 # Get the deserialized instance object
        student_serializer_obj = StudentSerializer(data=dic_data)

When the serializer calls the save method, it actually calls the create method in the serializer. (According to the parameters passed in when creating the object, it is judged whether to call the create method or the update method when executing the save method.

When building a serializer instance, only pass data= , and when calling save, the create method is called.

When building a serializer instance, pass data= and instance= at the same time, and when calling save, call the update method.

2. In the serializer, create the create method

 def create(self, validated_data: dict):
        project_obj = MiaoStudent.objects.create(**validated_data)
        return project_obj

The operation of the database will be executed in the create method.

in:

  1. validated_data: dict is the obtained user input data after validation, which is a dictionary.

3. Save method keyword parameter passing

Execute the save method.

student_serializer_obj.save()

Which fields are entered by the user, and which fields are used when operating the database.

Implementation function:

Not only do I want to get the fields entered by the user, but I also need to add some additional fields that I want to add to the program.

able to pass

.save(keyword 1:"value 1",keyword 2:"value 2")

incoming.

The create method is used to obtain, and the validated user passes in validated_data, which is a dictionary. This dictionary contains the additional data we just passed in.

Example:

passed in when calling save

student_serializer_obj.save(address="Beijing",hobby="play")

Execute the create method to retrieve additional data.

 def create(self, validated_data: dict):
        address = validated_data. pop("address")
        hobby = validated_data. pop("address")
        project_obj = MiaoStudent.objects.create(**validated_data)
        return project_obj

2.2 Serializer update method

In the views view, put the original code

 def put(self, request, pk):
        # 1. It is necessary to verify whether pk exists in the database
        # 2. Read project data from the database
        try:
            student_obj = MiaoStudent.objects.get(id=pk)
        except Exception as e:
            return JsonResponse({'msg': 'The parameter is wrong'}, status=400)

        # 3. Get the json parameter and convert it into a dictionary
        try:
            dic = json.loads(request.body)
        except Exception as e:
            return JsonResponse({'msg': 'The parameter is wrong'}, status=400)

        # 4. Serialization, converting the dictionary entered by the user into a serialized instance
        serializer_obj=StudentSerializer(data=dic)
        # 5. The serializer verifies the parameters passed in by the user
        # is_valid() data validation
        # serializer_obj.errors error message after verification
        if not serializer_obj.is_valid():
            return JsonResponse(serializer_obj. errors, status=400)

        # 6. Update data and operate the database
        student_obj.sname = serializer_obj.validated_data.get('sname')
        student_obj.sgender = serializer_obj.validated_data.get('sgender')
        student_obj.sid = serializer_obj.validated_data.get('sid')
        student_obj.sscore = serializer_obj.validated_data.get('sscore')
        student_obj.classid_id = serializer_obj.validated_data.get('classid_id')
        student_obj. save()

        # 7. Data display (not required). Convert the read item data into a dictionary
        serializer = StudentSerializer(instance=student_obj)
        return JsonResponse(serializer.data, status=201)

1. View function: When creating a serialized instance, use data= , instance=

student_obj = MiaoStudent.objects.get(id=pk)
dic = json.loads(request.body)
serializer_obj = StudentSerializer(data=dic, instance=student_obj)

The overall code of the modified view function

class StudentsDetailView(View):
    def get(self, request, pk):
        # 1. It is necessary to verify whether pk exists in the database

        # 2. Read project data from the database
        try:
            student_obj = MiaoStudent.objects.get(id=pk)
        except Exception as e:
            return JsonResponse({'msg': 'The parameter is wrong'}, status=400)
        serializer = StudentSerializer(instance=student_obj)

        return JsonResponse(serializer.data)

    def put(self, request, pk):
        # 1. It is necessary to verify whether pk exists in the database
        # 2. Read project data from the database
        try:
            student_obj = MiaoStudent.objects.get(id=pk)
        except Exception as e:
            return JsonResponse({'msg': 'The parameter is wrong'}, status=400)

        # 3. Get the json parameter and convert it into a dictionary
        try:
            dic = json.loads(request.body)
        except Exception as e:
            return JsonResponse({'msg': 'The parameter is wrong'}, status=400)

        # 4. Serialization, converting the dictionary entered by the user into a serialized instance
        # serializer_obj=StudentSerializer(data=dic)
        serializer_obj = StudentSerializer(data=dic, instance=student_obj)
        # 5. The serializer verifies the parameters passed in by the user
        # is_valid() data validation
        # serializer_obj.errors error message after verification
        if not serializer_obj.is_valid():
            return JsonResponse(serializer_obj. errors, status=400)

        # 6. Update data and operate the database
        # student_obj.sname = serializer_obj.validated_data.get('sname')
        # student_obj.sgender = serializer_obj.validated_data.get('sgender')
        # student_obj.sid = serializer_obj.validated_data.get('sid')
        # student_obj.sscore = serializer_obj.validated_data.get('sscore')
        # student_obj.classid_id = serializer_obj.validated_data.get('classid_id')
        # student_obj. save()
        serializer_obj. save()

        # 7. Data display (not required). Convert the read item data into a dictionary
        # serializer = StudentSerializer(instance=student_obj)
        return JsonResponse(serializer_obj.data, status=201)

2. The update method in the serializer

 def update(self, instance, validated_data: dict):
        # for key, value in validated_data.items():
        # setattr(instance, key, value)
        # validated_data is the data passed in by the user after verification

        instance.sname = validated_data.get('sname') or instance.sname
        instance.sgender = validated_data.get('sgender') or instance.sgender
        instance.sid = validated_data.get('sid') or instance.sid
        instance.sage = validated_data.get('sage') or instance.sage
        instance.sscore = validated_data.get('sscore') or instance.sscore
        instance.classid_id = validated_data.get('classid_id') or instance.classid_id
        instance. save()
        return instance
  1. or is for processing when the value is empty

The knowledge points of the article match the official knowledge files, and you can further learn relevant knowledgePython entry skill treeWeb application development Django298910 people are studying systematically