当我们在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将不知道存储什么,它会抛出一个错误。
|| blank = True || null = True && blank = True
class TestModel(models.Model):
field1 = models.CharField(max_length=100, null=True)
field2 = models.CharField(max_length=100, blank=True) # it's not a correct way
field3 = models.CharField(max_length=100, null=True, blank=True)
数据库字段:MySQL
CREATE TABLE TestModel (
`id` INT(10) NOT NULL AUTO_INCREMENT,
`field1` VARCHAR(100) NULL DEFAULT NULL,
`field2` VARCHAR(100) NOT NULL,
`field3` VARCHAR(100) NULL DEFAULT NULL,
)
case-01: null = True
db: db field is accepts null value
form: form field is `required`
NB: DB IS ACCEPTS NULL VALUE, BUT FORM FIELD IS REQUIRED. SO FORM IS
SUBMITTED WHEN THIS FIELD HAVE SOME VALUE. it's good.
case-02: blank = True
db: db field is not accepts null value
form: form field is `optional`
NB: FORM IS VALID WITHOUT ANY VALUE, BUT DB IS NOT ACCEPTS NULL VALUE.
SO THE FORM IS SUBMITTED WITHOUT ANY VALUE THEN BOOM. it's worst.
case-03: null = True && blank = True
db: db field is accepts null value
form: form field is `optional`
NB: HERE FORM FIELD IS OPTIONAL & FORM IS VALID WITHOUT ANY VALUE
& DB ALSO ACCEPTS NULL VALUE. SO, IT'S BEST TO USE `null=True && blank=True`
:)