null=True
blank=True
默认 = 0
有什么区别?你什么时候用什么?
最佳答案
直接来自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.
关于python - 在 Django models.py 中,default、null 和 blank 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4384098/