About Checking if a CharField is Not Empty

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

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

Django/Python Consulting

If you have a specific Django challenge or integration you'd like to solve, I'd be happy to help. Book a free 30-minute call to discuss your project, see if we're a good fit, and explore the best approach for your needs. After the call, you'll receive a tailored cost estimate based on what we discuss.