'How can I truncate serializer CharField value if it exceeds a certain length

I have a model field that I want to restrict to a certain length (max_length=2000). I however want the serializer to truncate any value that exceeds that length (max_length=2000) without failing the validation if a given string exceeds the limit. How can I achieve this

model field

description = models.CharField(max_length=2000)

serializer field

description = serializers.CharField(
        max_length=2000, required=False,
        allow_blank=True, default=""
    )

For example, if the serializer is called with a value of len= 2005, I want the validation to truncate the value to [:2000] and not raise an error.



Solution 1:[1]

you can use field-level validation to restrict the length of the string and do any custom operation that you want.

def validate_description(self, value):
    return value[:2000]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1