Validating data with serializers
One of the most loved features of DRF serializers is the data validation framework it provides out of the box. By default, whenever a model is defined to the model serializer, it automatically picks the field types and the database field validators, applying them to the serializer. When we pass raw data to the serializer and call the is_valid()
method, it evaluates the data against the autogenerated validators and gives us a Boolean value.
Now, let’s investigate a few in-depth concepts and the implementation of validators in DRF Serializers.
Customizing field-level validation
DRF serializer fields can have custom validation logic linked to a particular field. By defining a validate_<field name>
method in the serializer class, DRF automatically executes the validator whenever the is_valid()
method is called. For example, if we don’t want to have an underscore inside a title, we can use the following snippet:
class BlogCustom7Serializer...