当我们在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=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(而不是NOT null)。Django字段类型(如DateTimeField或ForeignKey)的空白值将在DB中存储为NULL。
Blank确定表单中是否需要该字段。这包括管理表单和自定义表单。如果blank=True,则该字段将不是必需的,而如果为False,则该字段不能为空。
这两者的组合非常常见,因为通常情况下,如果您要允许表单中的字段为空,您还需要数据库允许该字段为NULL值。例外是CharFields和TextFields,它们在Django中永远不会被保存为NULL。空白值作为空字符串存储在DB中(")。
举几个例子:
models.DateTimeField(blank=True) # raises IntegrityError if blank
models.DateTimeField(null=True) # NULL allowed, but must be filled out in a form
显然,使用这两个选项在逻辑上没有意义(尽管如果您希望一个字段在表单中始终是必需的,则可能存在null=True, blank=False的用例,当通过shell之类的东西处理对象时是可选的)。
models.CharField(blank=True) # No problem, blank is stored as ''
models.CharField(null=True) # NULL allowed, but will never be set as NULL
CHAR和TEXT类型永远不会被Django保存为NULL,所以NULL =True是不必要的。但是,您可以手动将其中一个字段设置为None以强制将其设置为NULL。如果你有一个场景,在那里可能是必要的,你仍然应该包括null=True。