Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django annotate whether field is null

Tags:

python

django

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)

like image 387
user972014 Avatar asked Mar 07 '26 11:03

user972014


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()
    )
)
like image 154
Willem Van Onsem Avatar answered Mar 09 '26 00:03

Willem Van Onsem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!