Django check: Avoid NULL for string fields

Avoid using NULL on string-based fields such as CharField and TextField, as the Django convention is to use the empty string.

Description

According to the Django documentation, 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.

One exception is when a CharField has both unique=True and blank=True set. In this situation, null=True is required to avoid unique constraint violations when saving multiple objects with blank values.

This check will alert on these cases, for example:

# SHOULD MATCH
from django.db import models
from django.db.models import Model

class ExampleModel(Model):
    #CharField should not set null = True
    fieldOne = models.CharField(
        max_length=200,
        null=True)

This check will not alert on these cases:

from django.db import models
from django.db.models import Model

class ExampleModel(Model):
    # when unique=True and blank=True, then null must be true
    # see exception paragraph above
    fieldThree = models.CharField(
        unique=True,
        null=True,
        blank=True,
        max_length=100
    )
    # this is neither CharField nor TextField
    notText = models.IntegerField(
        max_value=255
    )

References

  1. Django documentation