Django RAW SQL查询如何通过日期比较

dm7nw8vv  于 2022-11-18  发布在  Go
关注(0)|答案(1)|浏览(110)

我使用DjangoRawSQL是因为我想构建一个相对复杂的查询,
作为它的一部分,我有一个case语句,它说“如果记录上的日期〈今天,那么1,否则0 --这是有效的。

overdue_phases = task.objects.filter(orgid=orgid, taskid=taskidx).raw('''
    
     SELECT '1' as id, case when research_due < "2022-12-01" AND research_status != "done" then 1 else 0 end as count     
     from app_task where taskid = "''' + taskidx + '''"''')
                   
overdue_phases = task.objects.filter(orgid=orgid, taskid=taskidx).raw('''

 SELECT '1' as id, case when research_due < "2022-12-01" AND research_status != "done" then 1 else 0 end as count     
 from app_task where taskid = "''' + taskidx + '''"''')

然而,当我想用TODAY()替换硬编码的日期时,我无法让它工作。我试着将一个python日期变量传递到脚本中(td = datetime.date.today()),但它没有返回正确的结果!
有人能给我点建议吗?

up9lanfz

up9lanfz1#

没有必要这么做。你可以使用 * 条件表达式 * [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),
    )
)

或者,如果布尔值也足够:

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')
)

或者对于带有**ExpressionWrapper**[Django-doc]的旧版本Django:

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

可以将'2022-12-01'替换为date.today()

相关问题