首页 > 解决方案 > 如何为注释django提供条件以返回布尔字段

问题描述

我正在尝试为注释字段提供条件以返回BooleanField

class Employee(models.Model):
    date_of_expire = models.DateTimeField()

我的观点.py

from django.db.models import Case,When,BooleanField
def lists(request):
    lists = Employee.objects.annotate(is_expire=Case(When(
        date_of_expire__lte=timezone.now()
        ),output_field=BooleanField())).order_by('-date_of_expire')
    #others

但它不起作用,即使某些对象date_of_expire小于当前时间,仍然返回所有现有数据

请问还有什么我应该尝试的吗?

标签: djangoannotations

解决方案


正如@willem Van Onsem 先生在评论中提到的一个链接

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

lists = Employee.objects.annotate(is_expire=ExpressionWrapper(Q(date_of_expire__lte=timezone.now()),output_field=BooleanField()).order_by('-date_of_expire')

表达式包装器


推荐阅读