当我们在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的优点/缺点是什么?


当前回答

null - default为False 如果为True, Django将在数据库中存储为null。

blank - default为False 如果为真,则允许该字段为空

更多的钱,转到 https://docs.djangoproject.com/en/3.0/topics/db/models/

其他回答

下表显示了主要的区别:

+--------------------------------------------------------------------+
| Purpose                  | null=True        | blank = True         |
|--------------------------|------------------|----------------------|
| Field can be empty in DB | Do this          | Unaffected           |
|--------------------------|------------------|----------------------|
| ModelForm(required field)| Unaffected       | field not required   |
|--------------------------|------------------|----------------------|
| Form Validation          | Unaffected       | field not required   |
|--------------------------|------------------|----------------------|
| on_delete=SET_NULL       | Need this        | Unaffected           |
+--------------------------------------------------------------------+

这里,是null=True和blank=True的主要区别:

null和blank的默认值都是False。这两个值都在字段级工作,即,我们是否想要保持字段为空或空白。

null=True将字段的值设置为null,即没有数据。它基本上是为数据库列的值。

date = models.DateTimeField(null=True)

blank=True确定表单中是否需要该字段。这包括管理表单和您自己的自定义表单。

title = models.CharField(blank=True) // title可以为空。 在数据库中(“”)将被存储。 null=True blank=True这意味着该字段在所有情况下都是可选的。

epic = models.ForeignKey(null=True, blank=True)
// The exception is CharFields() and TextFields(), which in Django are never saved as NULL. Blank values a
null = True

意味着没有数据库对要填充的字段的约束,因此您可以有一个具有此选项的填充的空值对象。

blank = True

意味着在django表单中没有验证约束。所以当你为这个模型填写一个modelForm时,你可以不填这个选项。

当你说null=False时,这意味着数据必须传递到数据库保存。当你说空白=False时,这意味着数据必须从前端输入,反之亦然

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空白