【发布时间】:2021-04-30 15:49:43
【问题描述】:
我有一个 Django 模型 DocumentComments,有两个日期时间字段 created 和 updated。我正在开发一个搜索函数,它解析搜索字符串并返回 Q 表达式,以根据搜索字符串中的值查询 DocumentComments 模型。
我需要写类似Q(created.year=xxxx) 的内容,其中created.year 是created 日期时间字段中的年份。但是 Django 整个上午都在告诉我“关键字不能是表达式”。
我尝试使用自定义模型管理器并使用年份字段注释默认查询集,但这不起作用,因为我似乎无法访问 get_queryset 函数中的 created.year 值。
class DocumentCommentManager(models.Manager):
def get_queryset(self):
c_year = self.created.year
u_year = self.updated.year
return super(DocumentCommentManager, self).get_queryset().annotate(created_year=c_year, updated_year=u_year)
我缺少什么,或者有什么更好的方法来实现我的目标?
谢谢!
标记
【问题讨论】:
标签: django-queryset django-managers django-q django-3.1