Search code examples
djangodjango-modelsdjango-orm

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?


Solution

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