Django max_length for IntegerField

Django ignores max_length for integer fields, and will warn you in Django 1.8+. See ticket 23801 for more details.

You can either use a max value validator,

from django.core.validators import MaxValueValidator

class MyModel(models.Model):
    ...
    id_student = models.PositiveIntegerField(primary_key=True, validators=[MaxValueValidator(9999999999)])

or use a CharField to store the id, and use a regex validator to ensure that the id is entirely made of digits. This would have the advantage of allowing ids that start with zero.

from django.core.validators import RegexValidator

class MyModel(models.Model):
    ...
    id_student = models.CharField(primary_key=True, max_length=10, validators=[RegexValidator(r'^\d{1,10}$')])

Leave a Comment