Order of Serializer Validation in Django REST Framework

后端 未结 4 447
天涯浪人
天涯浪人 2020-11-28 02:59

Situation

While working with validation in the Django REST Framework\'s ModelSerializer, I have noticed that the Meta.model

4条回答
  •  南笙
    南笙 (楼主)
    2020-11-28 03:17

    I was also trying to understand how the control flows during serializer validation and after carefully going through the source code of djangorestframework-3.10.3 I came up with below request flow diagram. I have described the flow and what happens in the flow to the best of my understanding without going into too much detail as it can be looked up from source.

    Ignore the incomplete method signatures. Only focusing on what methods are called on what classes.

    Assuming you have an overridden is_valid method on your serializer class (MySerializer(serializers.Serializer)) when you call my_serializer.is_valid() the following takes place.

    1. MySerializer.is_valid() is executed.
    2. Assuming you are calling the super class (BaseSerializer) is_valid method (like: super(MySerializer, self).is_valid(raise_exception) in your MySerializer.is_valid() method, that will be called.
    3. Now since MySerializer is extending serializers.Serializer, the run_validation() method from serializer.Serializers is called. This is validating only the data dict the first. So we haven't yet started field level validations.
    4. Then the validate_empty_values from fields.Field gets called. This again happens on the entire data and not a single field.
    5. Then the Serializer.to_internal_method is called.
    6. Now we loop over each fields defined on the serializer. And for each field, first we call the field.run_validation() method. If the field has overridden the Field.run_validation() method then that will be called first. In case of a CharField it is overridden and calls the run_validation method of Field base class. Step 6-2 in the figure.
    7. On that field we again call the Field.validate_empty_values()
    8. The to_internal_value of the type of field is called next.
    9. Now there is a call to the Field.run_validators() method. I presume this is where the additional validators that we add on the field by specifying the validators = [] field option get executed one by one
    10. Once all this is done, we are back to the Serializer.to_internal_value() method. Now remember that we are doing the above for each field within that for loop. Now the custom field validators you wrote in your serializer (methods like validate_field_name) are run. If an exception occurred in any of the previous steps, your custom validators wont run.
    11. read_only_defaults()
    12. update validate data with defaults I think
    13. run object level validators. I think the validate() method on your object is run here.

提交回复
热议问题