Django REST Framework Serializers - custom field validation


DRF tip:

You can add custom field validation to your serializer.

The validation method needs to be named like so: validate_<field_name>.

For example:

class PersonSerializer(serializers.ModelSerializer):
    class Meta:
        model = Person
        fields = ['name', 'age']

    def validate_age(self, value):
        if value < 18:
            raise serializers.ValidationError('The person has to be at least 18 years old.')
        return value

For more, review Custom Data Validation.