【问题标题】:How to add a calculated field to a django query expression如何将计算字段添加到 django 查询表达式
【发布时间】:2021-04-30 15:49:43
【问题描述】:

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

我需要写类似Q(created.year=xxxx) 的内容,其中created.yearcreated 日期时间字段中的年份。但是 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


    【解决方案1】:

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

    我的 DocumentCommentManager:

    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 表达式将计算字段添加到模型查询的通用方法。如果您可以分享任何示例,那就太好了!

    【讨论】:

      猜你喜欢
      • 2013-07-14
      • 2018-03-10
      • 2011-02-01
      • 1970-01-01
      • 2019-12-12
      • 1970-01-01
      • 1970-01-01
      • 2017-02-07
      相关资源
      最近更新 更多