Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Query - Annotate With Boolean Value From Date Comparison

I want to write a query which will have an annotation of expired based on a comparison of a date in the model and the date/time of now and receive a boolean value depending on the outcome. I can't find how this is done.

I have tried the below so far:

.annotate(expired=F( F('date_updated') > datetime_now))

Can someone let me know the way to achive this?

like image 220
OptimusPrime Avatar asked Jul 23 '26 01:07

OptimusPrime


1 Answers

You can annotate the objects with a BooleanField that is the result of a condition with an ExpressionWrapper [Django-doc]:

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

MyModel.objects.annotate(
    expired=ExpressionWrapper(
        Q(date_updated__gt=datetime_now),
        output_field=BooleanField()
    )
)
like image 200
Willem Van Onsem Avatar answered Jul 25 '26 10:07

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!