当我们在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=true时,如果字段没有填充,它将在你的数据库中设置为空。如果 你设置blank=true,它不会为该字段设置任何值。

其他回答

当我们在Django管理中保存任何东西时,会发生两步验证,在Django级别和数据库级别。我们不能在数字字段中保存文本。

数据库的数据类型是NULL,什么都不是。当Django在数据库中创建列时,它指定它们不能为空。如果你试图保存NULL,你会得到数据库错误。

同样在Django- admin级别,默认情况下所有字段都是必须的,你不能保存空白字段,Django会给你一个错误。

所以,如果你想保存空白字段,你需要在Django和数据库级别上允许它。 blank=True -在管理面板中允许空字段 null=True -将允许将null保存到数据库列。

Null是数据库和空白是字段验证,你想显示在用户界面上,如textfield,以获得人的姓。 如果lastname =模型。Charfield (blank=true)它没有要求用户输入姓氏,因为这是可选字段现在。 如果lastname =模型。Charfield (null=true),那么这意味着如果这个字段没有从user得到任何值,那么它将存储在数据库作为一个空字符串“”。

你可能有你的答案,但直到今天,很难判断是否把null=True或空白=True或两者都放在一个字段。我个人认为为开发者提供这么多选择是非常无用和令人困惑的。让它按自己的意愿处理空值或空格。

下面是来自Two Scoops of 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