Skip to content

[DJ01] Avoid using null=True on string based fields such as CharField and TextField

Rocio Aramberri edited this page Jan 19, 2021 · 4 revisions

It is considered a bad practice to allow NULL values in a string-based field. By allowing null values on a string-based field there would be two values that would indicate no data: NULL or empty string. To avoid redundancy, the Django convention is to use an empty string.

There is an exception for this rule when unique=True and blank=True since an empty string value would not be unique.

String-based fields include:

  • CharField
  • TextField
  • EmailField
  • URLField
  • SlugField
  • FilePathField
  • URLField

Don't

from django.db import models


class Post(models.Model):
    title = models.CharField(max_length=150, null=True, blank=True)

Do

from django.db import models


class Post(models.Model):
    title = models.CharField(max_length=150, blank=True)

References

https://docs.djangoproject.com/en/3.0/ref/models/fields/#django.db.models.Field.null