Django REST Framework Serializers - function validators


DRF tip:

If you need the same validation in multiple serializers, you can create a function validator instead of repeating the code.

For example:

# function validator:
def is_rating(value):
    if value < 1:
        raise serializers.ValidationError('Value cannot be lower than 1.')
    elif value > 10:
        raise serializers.ValidationError('Value cannot be higher than 10')


# function validator used in a serializer
class MovieSerializer(serializers.ModelSerializer):
    rating = IntegerField(validators=[is_rating])

For more, review Custom Data Validation.