[Django]-How to set max length on integerfield Django Rest

3πŸ‘

βœ…

Can you try something like below? (code not tested.)

#add this import statement at top

from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _

#A function to check length
def validate_length(value):
    an_integer = value
    a_string = str(an_integer)
    length = len(a_string)
    if length > 10:
        raise ValidationError(
            _('%(value)s is above 10 digits')
        )

#Add to model field
class MyModel(models.Model):
    validate_len = models.IntegerField(validators=[validate_length])

refer below
https://docs.djangoproject.com/en/3.2/ref/validators/

0πŸ‘

The RegexValidator could be used with the correct regex. If changing IntegerField to CharField isn’t a big deal, you could also write a validator to ensure code has a 10 digit maximum. It could be a custom validator that verifies each character is a digit and there are less than 10 total along with any other requirements you may have.

πŸ‘€purple

Leave a comment