Django annotate whether field is null

Viewed 2461

I want to annotate a datetime field to know whether it is null. Something like:

Table.objects.all().annotate(date_is_null=XXX(YYY)).values(date_is_null, .....)

What do I need to replace XXX(YYY) to check if the field is null?

(I'm using .values().annotate() later for a Group By, so it must be in annotate first)

1 Answers

You can use an ExpressionWrapper to convert a Q object to an annotated BooleanField:

from django.db.models import BooleanField, ExpressionWrapper, Q

Table.objects.annotate(
    date_is_null=ExpressionWrapper(
        Q(date=None),
        output_field=BooleanField()
    )
)

Here Q(date=None) is thus the condition. If the DateTimeField has a different name, you should alter the condition accordingly.

You can make the condition more verbose with:

from django.db.models import BooleanField, ExpressionWrapper, Q

Table.objects.annotate(
    date_is_null=ExpressionWrapper(
        Q(date__isnull=True),
        output_field=BooleanField()
    )
)
Related