当我们在Django中添加模型字段时,我们通常这样写:

models.CharField(max_length=100, null=True, blank=True)

ForeignKey, DecimalField等也是如此。两者的基本区别是什么:

null = True只 空白= True只 null=True, blank=True

对于不同的(CharField, ForeignKey, ManyToManyField, DateTimeField)字段?使用选项1、2或3的优点/缺点是什么?


当前回答

Blank=False # this field is required.
Null=False # this field should not be null

Blank=True # this field is optional.
Null=True # Django uses empty string (''), not NULL.

注意: 避免在基于字符串的字段上使用null=True,例如CharField和TextField和FileField/ImageField。

参考:Django null, Django空白

其他回答

blank=True可以设置为任何模型字段,以控制在表单中输入值时该字段是否可以留空。这里,我们讨论的是输入数据。

null=True, if we set blank=True for a field, that model field does not receive any value, then the database or Django has to do something with that field when data is written into the database. For any kind of text content an empty string is stored in the database, so there is a value stored in the database. For other kinds of fields like date fields or numbers, we use the special data type "null". "null" can be used if a field potentially has no value, but by default, Django does not allow "null" values. That is why you need to explicitly set null=True.

假设你为任何非文本字段设置了blank=True,但你没有指定“null=True”,Django将不知道存储什么,它会抛出一个错误。

如果设置null=True,它将允许将数据库列的值设置为null。如果你只设置blank=True, django会为这个列设置默认的新值为""。

有一点,null=True将是必要的,即使在CharField或TextField,这是当数据库有唯一的标志设置列。在这种情况下,你需要使用这个:

a_unique_string = models.CharField(blank=True, null=True, unique=True)

最好跳过null=True的非唯一CharField或TextField。否则,一些字段将被设置为NULL,而另一些字段将被设置为“”,并且您必须每次检查字段值是否为NULL。

简单的null=True定义了数据库应该接受null值,另一方面,空白=True定义了表单验证该字段应该接受空白值或不接受空白值(如果空白=True,则接受该字段中没有值的表单,空白=False[默认值],则表单验证将显示此字段是必需的错误。

null=与数据库相关的True/False

blank=与表单验证相关的真/假

简单地说,

Blank和null不同。

Null是纯粹与数据库相关的,而blank是与验证相关的(表单要求)。

如果null=True, Django将在数据库中存储空值为null。如果字段有blank=True,表单验证将允许输入空值。如果一个字段有blank=False,该字段将是必需的。

这里有一个blank= True和null=True字段的示例

description = models.TextField(blank=True, null= True)

在这种情况下: blank = True:告诉我们的表单可以将description字段保留为空

and

null = True:告诉我们的数据库,在我们的db字段中记录一个空值并且不给出错误是可以的。