[Solved]-Django annotate whether field is null

22👍

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()
    )
)

Leave a comment