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
Also by me
Django Messaging 🎅🏼
For Django-based social platforms.
Django Paddle Subscriptions 🎅🏼
For Django-based SaaS projects.
Django GDPR Cookie Consent 🎅🏼
For Django websites that use cookies.