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(
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()
)
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With