当我们在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.db.models中的字段属性。Null是与数据库相关的,而空白是与验证相关的。
null
默认值为null=False。如果null=False, Django将不允许在数据库列中使用null值。
如果null=True, Django会将数据库列中的空值存储为null。对于CharField和TextField, django将使用空字符串"而不是NULL。避免为CharField和TextField使用空属性。一个例外是,当CharField具有unique=True和blank=True时,则需要null=True。
空白
默认为空白=False。如果blank=False,该字段将是必需的。
如果blank=True,该字段是可选的,可以留空。blank=True和null=False将需要在模型上实现clean()以编程方式设置任何缺失的值。
默认值为“null”和“blank”为“False”。
Null:与数据库相关。定义给定的数据库列是否接受空值。
Blank:这是验证相关的。它将在表单验证期间调用form.is_valid()时使用。
也就是说,有一个null=True和blank=False的字段是完全没问题的。意思是在数据库级别上,该字段可以为NULL,但在应用程序级别上,它是必需的字段。
现在,大多数开发人员都犯了错误:为基于字符串的字段(如CharField和TextField)定义null=True。避免这样做。否则,你最终会有两个可能的“无数据”值,即:None和一个空字符串。对于“无数据”有两个可能的值是多余的。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将不知道存储什么,它会抛出一个错误。