How to set max length on integerfield Django Rest

Viewed 1072

Okay so I need to have my field have a maximum of 10 integers allowed to be entered. I tried MaxValueValidator but I figured out that this just needs a value thats lower than the set value. I want to be able to enter a maximum of 10 numbers, so it should work if I enter just one number, but also if I enter 10.

Code ex:

class Random(models.Model):
     code=models.IntegerField
2 Answers

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/

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.

Related