Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django max_length for IntegerField

I have this model field:

id_student = models.PositiveIntegerField(primary_key=True, max_length=10) 

The max_length restriction doesn't work. I can log in to the admin and create a student with an id with more than 10 chars. How can I solve this?

like image 455
Alejandro Veintimilla Avatar asked Jun 15 '15 16:06

Alejandro Veintimilla


People also ask

Can IntegerField be negative Django?

The IntegerField is used to store integer values from -2147483648 to 2147483647 ( 4 Bytes ). default parameter is not mandatory. But it's useful to set a default value. Like an IntegerField, but must be either positive or zero (0).

What is Max_length in Django?

The Django DB Docs will tell you, that max_length=255 is guaranteed to work always. If you need something of the amount you've specified in your question, I'd suggest to use a TextField.

What is null false in Django?

null. If True , Django will store empty values as NULL in the database. Default is False .


1 Answers

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}$')]) 
like image 72
Alasdair Avatar answered Sep 28 '22 12:09

Alasdair