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?
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).
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.
null. If True , Django will store empty values as NULL in the database. Default is False .
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}$')])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With