Difference between null and blank in Django

In Django's model fields:

  • blank controls the validation at the application level (Django's own input validation mechanisms)
  • null controls the validation at the database level

Make a field optional

All fields are required by default.

  • blank=True tells Django that the field can be left empty (in forms)
  • null=True tells the database that the field can be left empty (NULL)

So to make a field optional:

pub_time = models.TimeField(blank=True, null=True)

Make a string-based field optional

For string-based fields, Django saves an empty string when blank=True:

title = models.CharField(blank=True)

This is because of a convention in Django that recommends the use of '' to represent the empty value for string-based fields:

Avoid using null on string-based fields such as CharField and TextField.

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.

Further reading

Avant TypeScript in React Après Apprendre comment apprendre

Tag Kemar Joint