IntegerField 的 Django max_length [英] Django max_length for IntegerField
问题描述
我有这个模型字段:
id_student = models.PositiveIntegerField(primary_key=True, max_length=10)
max_length
限制不起作用.我可以登录到管理员并创建一个 id 超过 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?
推荐答案
Django 忽略整数字段的 max_length
,并在 Django 1.8+ 中会警告你.有关详细信息,请参阅 ticket 23801.
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)])
或使用 CharField
来存储 id,并使用正则表达式验证器来确保 id 完全由数字组成.这将具有允许以零开头的 id 的优点.
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}$')])
这篇关于IntegerField 的 Django max_length的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!