About Checking if a CharField is Not Empty

Here's how you can check if a CharField is not empty in a Queryset:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
from django.db import models
from django.db.models.functions import Length
from pictures.models import Picture

models.CharField.register_lookup(Length, "length")

qs = Picture.objects.annotate(
    alt_text_exists=models.Case(
        models.When(
            alt_text__length__gt=0,
            then=models.Value(True)
        ),
        default=models.Value(False),
        output_field=models.BooleanField(),
    )
)
# Get pictures with missing Alt Text
qs = qs.filter(alt_text_exists=False)

Note that to check the length of a string, you must register the new lookup for the field type.

Tips and Tricks Programming Development Databases Django 4.2 Django 3.2 Django 2.2 PostgreSQL MySQL