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

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

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

其他回答

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

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

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

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

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

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

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

简单来说就是答案:-

通过null = True,我们告诉数据库模型的这个字段可以为null,通过blank = True,我们告诉Django模型的这个字段可以为null

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

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

blank = True

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