blank vs. null
In Django's model fields:
-
blank- controls the validation at the application level (Django's own input validation mechanisms)
- tells Django that the field can be left empty in forms
-
null- controls the validation at the database level
- tells the database that the field can be left empty (
NULL)
Making a field optional
All fields are required by default.
Non-string-based field
To make a non-string-based field optional:
pub_time = models.TimeField(blank=True, null=True)
String-based field
To make a string-based field optional, the Django convention is to avoid using null=True:
title = models.CharField(blank=True)
Indeed, Django saves an empty string when blank=True:
Avoid using
nullon string-based fields such asCharFieldandTextField.If a string-based field has
null=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;” the Django convention is to use the empty string, not
NULL.
SQL queries are easier to write when there is only one possible value for "no data".
But of course, if NULL and '' represent different things in a given use case, then null=True should be used for string-based fields.