django - 如何为注释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
小于当前时间,仍然返回所有现有数据
请问还有什么我应该尝试的吗?
解决方案
正如@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')
推荐阅读
- angular - 如何处理 Firebase 身份验证状态的响应时间
- javascript - 基于旧数据的预测/预测
- javascript - 再次运行 puppeteer 函数直到完成
- python - 流连接丢失:AssertionError(('_AsyncTransportBase._produce() tx 缓冲区大小下溢', -275, 1),)
- c++ - 如何将文件发送到服务器
- java - 如何清除 EditText 中的文本?
- c++ - 如何在 C++ 中创建子类
- c++ - 如何在 CppUTest 中使用 MockSupportPlugin 自动执行 checkExpectations?
- kubernetes - 我们可以增加 Kubernetes 中每个节点的 pod 数量吗?
- html - 导航栏下具有剩余视口高度的响应列