[Answered ]-Django RAW SQL query how to pass date comparison

1👍

There is no need to do this. You can use condition expressions [Django-doc]:

from django.db.models import Case, Q, Value, When

overdue_phases = task.objects.filter(orgid=orgid, taskid=taskidx).annotate(
    count=Case(
        When(
            ~Q(research_status='done'),
            research_due__lt='2022-12-01',
            then=Value(1),
        ),
        default=Value(0),
    )
)

Or if a boolean is sufficient as well:

from django.db.models import Q

overdue_phases = task.objects.filter(orgid=orgid, taskid=taskidx).annotate(
    count=~Q(research_status='done') & Q(research_due__lt='2012-12-01')
)

or for older versions of Django with an ExpressionWrapper [Django-doc]:

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

overdue_phases = task.objects.filter(orgid=orgid, taskid=taskidx).annotate(
    count=ExpressionWrapper(
        ~Q(research_status='done') & Q(research_due__lt='2012-12-01'),
        output_field=BooleanField(),
    )
)

You can replace '2022-12-01' with date.today().

Leave a comment