Nullable string field

ORM queries and Python code are made more complex because values will sometimes be None and other times str.

The null attribute specifies that the field can be None (null at database level). This is useful for optional fields.

This adds complexity as the data type is inconsistent: some instances may be strings and others None. This complicates ORM queries and extra code must guard against performing str operations on a NoneType.

This problem is avoided by specifying default='' instead. The database will even throw an exception if there is an attempt to explicitly save None, thus avoiding bad data.

So in practice, do this

class Feedback(models.Model):
    comment = models.CharField(default='')

for feedback in Feedback.objects.filter(comment=''):
    # using feedback.comment is simple: it is always a str

Instead of this

class Feedback(models.Model):
    comment = models.CharField(null=True)

query = Q(comment__isnull=True) | Q(comment='')
for feedback in Feedback.objects.filter(query):
    # ensure comment is always str (can be None)
    comment = feedback.comment or ''

Are you affected? Check with
pip install django-doctor

Configuring this check

Django Doctor will run this check by default. No configuration is needed but the check can be turned on/off using check code nullable-string-field in your pyproject.toml file.

Read more about configuring Django Doctor.