0

我有一个 Django 模型,DocumentComments有两个日期时间字段createdupdated. 我正在研究一个搜索函数,它解析搜索字符串并返回一个 Q 表达式,以DocumentComments根据搜索字符串中的值查询模型。

我需要写一些类似的东西,日期时间字段中的年份在Q(created.year=xxxx)哪里。但是,正如 Django 整个上午都在告诉我的那样,“关键字不能是表达式”。created.yearcreated

我尝试使用自定义模型管理器并使用年份字段注释默认查询集,但这不起作用,因为我似乎无法访问函数created.year中的值get_queryset

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)

我错过了什么,或者有什么更好的方法来实现我的目标?

谢谢!

标记

4

1 回答 1

0

我能够使用 Django 的 db 函数 Extract ( https://docs.djangoproject.com/en/3.1/ref/models/database-functions/#extract )解决我的问题

我的文档评论管理器:

from django.db.models.functions import Extract

class DocumentCommentManager(models.Manager):
       def get_queryset(self):
          return super(DocumentCommentManager, self).get_queryset().annotate(created_year=Extract("created","year"))

这解决了我在模型查询中添加计算的日期时间字段的原始问题。

我仍然没有找到使用 Q 表达式将计算字段添加到模型查询的通用方法。如果您可以分享任何示例,那就太好了!

于 2021-01-27T17:40:33.163 回答