In Django models.py, what's the difference between default, null, and blank?
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.
From docs:
null
If True, Django will store empty values as NULL in the database. Default is False.
blank
If True, the field is allowed to be blank. Default is False.
default
The default value for the field.
You can use "default
" to set the value that will be used for the field in question should your code not explicitly set it to a value.
Use "blank
" for form validation purposes - blank=True will allow the field to be set to an empty value
Use "null
" if you would like to store an empty value as "null" in the DB. Often it's preferred, however, to set blank values to an empty string or to 0 as appropriate for a given field.
I know you already have your answer however till this day it's difficult to judge whether to put null=True
or blank=True
or both
to a field. I personally think it's pretty useless and confusing to provide so many options to developers. Let the handle the nulls or blanks however they want.
I follow this table (from the book "Two Scoops of Django"):