简体   繁体   中英

Django annotate whether field is null

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)

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(
        ,
        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(
        ,
        output_field=BooleanField()
    )
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM