Django 模型空白=假不起作用? [英] Django model blank=False does not work?
问题描述
我在 Django 1.5 中有以下模型:
I have the following model in Django 1.5:
class Person(models.Model):
name = models.CharField(max_length=50)
注意根据https://docs.djangoproject.com/en/dev/ref/模型/字段/name.blank 默认为 False,这意味着它必须被指定.
Note that according to https://docs.djangoproject.com/en/dev/ref/models/fields/ name.blank is by default False which means it must be specified.
但是,我可以成功创建一个 Person 对象,如下所示:
However, I could successfully create a Person object as follows:
Person.objects.create()
请注意未指定名称.这是怎么回事?
Notice the name is not specified. What is going on?
好的,文档的答案是:
请注意,这与 null 不同.null 纯粹与数据库相关,而空白与验证相关.如果一个字段有空白=True,表单验证将允许输入一个空值.如果某个字段有空白 = False,则该字段将是必需的.
Note that this is different than null. null is purely database-related, whereas blank is validation-related. If a field has blank=True, form validation will allow entry of an empty value. If a field has blank=False, the field will be required.
另一个问题:
请注意,当您保存模型时,验证器不会自动运行,但如果您使用的是 ModelForm,它将在表单中包含的任何字段上运行您的验证器.
Note that validators will not be run automatically when you save a model, but if you are using a ModelForm, it will run your validators on any fields that are included in your form.
如果您不使用表单,则有责任在保存之前调用 clean 方法.
It's your responsibility to call the clean methods before saving if you're not using a form.
推荐答案
blank
仅适用于表单字段验证,如 admin、django 表单等.null
另一方面是数据库级别的可空列.
blank
only applies to form field validation as in the admin, django forms, etc.
null
on the other hand is a database level nullable column.
至于为什么空白会导致默认的 ''
,我真的只是接受它,因为这就是它的工作方式",但它似乎出现在 django.db 中.模型.字段
As for why blank results in a default ''
, I had really just accepted it as "that's the way it works" but here's where it appears to be in django.db.models.Field
def get_default(self):
"""
Returns the default value for this field.
"""
if self.has_default():
if callable(self.default):
return self.default()
return force_unicode(self.default, strings_only=True)
if (not self.empty_strings_allowed or (self.null and
not connection.features.interprets_empty_strings_as_nulls)):
return None
return ""
# ^ this
这篇关于Django 模型空白=假不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!