在Django models.py中,默认值,null和blank之间有什么区别? [英] In Django models.py, what's the difference between default, null, and blank?
问题描述
null = True
blank = True
default = 0
有什么区别?何时使用什么?
直接从 Django model field reference :
code> Field.null
如果
True
Django将在数据库中存储空值为NULL
。默认为False
。
请注意,空字符串值总是存储为空字符串,而不是
NULL
。对非字符串字段(如整数,布尔和日期)只能使用null = True
。对于两种类型的字段,如果您要允许表单中的空值,您还需要设置blank = True
,如null
参数只影响数据库存储(参见blank
)。
在
CharField
和TextField
之类的基于字符串的字段上,除非有一个很好的原因,否则 。如果基于字符串的字段具有null = True
,那意味着它对于无数据有两个可能的值:NULL和空字符串。在大多数情况下,对无数据有两个可能的值是多余的:Django约定是使用空字符串,而不是NULL
。
Field.blank
如果
True
,则该字段允许为空。默认为False
。
注意,这不同于
null
。null
纯粹是数据库相关的,而blank
是与验证相关的。如果一个字段blank = True
,Django的管理网站上的验证将允许输入一个空值。如果字段blank = False
,则将需要该字段。
Field.default
b
$ b字段的默认值。这可以是值或可调用对象。
你不明白这一切吗?
null=True blank=True default = 0
What's the difference? When do you use what?
Direct from Django model field reference:
Field.null
If
True
, Django will store empty values asNULL
in the database. Default isFalse
.Note that empty string values will always get stored as empty strings, not as
NULL
. Only usenull=True
for non-string fields such as integers, booleans and dates. For both types of fields, you will also need to setblank=True
if you wish to permit empty values in forms, as thenull
parameter only affects database storage (seeblank
).Avoid using
null
on string-based fields such asCharField
andTextField
unless you have an excellent reason. If a string-based field hasnull=True
, that means it has two possible values for "no data": NULL, and the empty string. In most cases, it’s redundant to have two possible values for "no data;" Django convention is to use the empty string, notNULL
.
Field.blank
If
True
, the field is allowed to be blank. Default isFalse
.Note that this is different than
null
.null
is purely database-related, whereasblank
is validation-related. If a field hasblank=True
, validation on Django’s admin site will allow entry of an empty value. If a field hasblank=False
, the field will be required.
Field.default
The default value for the field. This can be a value or a callable object. If callable it will be called every time a new object is created.
Do you not understand all this?
这篇关于在Django models.py中,默认值,null和blank之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!