我希望在我的模型中有一个固定长度的 CharField。换句话说,我希望只有指定的长度是有效的。
我试着做类似的事情
volumenumber = models.CharField('Volume Number', max_length=4, min_length=4)
但它给了我一个错误(似乎我可以同时使用 max_length 和 min_length)。
还有其他快捷方式吗?
我的模型是这样的:
class Volume(models.Model):
vid = models.AutoField(primary_key=True)
jid = models.ForeignKey(Journals, db_column='jid', null=True, verbose_name = "Journal")
volumenumber = models.CharField('Volume Number')
date_publication = models.CharField('Date of Publication', max_length=6, blank=True)
class Meta:
db_table = u'volume'
verbose_name = "Volume"
ordering = ['jid', 'volumenumber']
unique_together = ('jid', 'volumenumber')
def __unicode__(self):
return (str(self.jid) + ' - ' + str(self.volumenumber))
我想要的是 volumenumber
必须正好是 4 个字符。
即 如果有人插入“4b”,django 会给出一个错误,因为它需要一个 4 个字符的字符串。
所以我尝试了
volumenumber = models.CharField('Volume Number', max_length=4, min_length=4)
但它给了我这个错误:
Validating models...
Unhandled exception in thread started by <function inner_run at 0x70feb0>
Traceback (most recent call last):
File "/Library/Python/2.5/site-packages/django/core/management/commands/runserver.py", line 48, in inner_run
self.validate(display_num_errors=True)
File "/Library/Python/2.5/site-packages/django/core/management/base.py", line 249, in validate
num_errors = get_validation_errors(s, app)
File "/Library/Python/2.5/site-packages/django/core/management/validation.py", line 28, in get_validation_errors
for (app_name, error) in get_app_errors().items():
File "/Library/Python/2.5/site-packages/django/db/models/loading.py", line 131, in get_app_errors
self._populate()
File "/Library/Python/2.5/site-packages/django/db/models/loading.py", line 58, in _populate
self.load_app(app_name, True)
File "/Library/Python/2.5/site-packages/django/db/models/loading.py", line 74, in load_app
models = import_module('.models', app_name)
File "/Library/Python/2.5/site-packages/django/utils/importlib.py", line 35, in import_module
__import__(name)
File "/Users/Giovanni/src/djangoTestSite/../djangoTestSite/journaldb/models.py", line 120, in <module>
class Volume(models.Model):
File "/Users/Giovanni/src/djangoTestSite/../djangoTestSite/journaldb/models.py", line 123, in Volume
volumenumber = models.CharField('Volume Number', max_length=4, min_length=4)
TypeError: __init__() got an unexpected keyword argument 'min_length'
如果我只使用“max_length”或“min_length”,那显然不会出现。
我阅读了 django 网站上的文档,看来我是对的(我不能同时使用两者)所以我想问是否有另一种方法可以解决这个问题。
最佳答案
有点像上面一样,但是对于它的值(value),你也可以继续使用 django 提供的 MinLengthValidator。为我工作。代码看起来像这样:
from django.core.validators import MinLengthValidator
...
class Volume(models.Model):
volumenumber = models.CharField('Volume Number', max_length=4, validators=[MinLengthValidator(4)])
...
关于django - 固定长度的CharField,怎么样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2470760/