python - Django 不知何故无法确定简单的注释函数

标签 python django python-3.x django-models django-queryset

我正在尝试在查询集类上创建一个注释,该注释仅添加一个 bool 值,该 bool 值是某些标准查询的结果。

CustomQueryset(models.QuerySet):
    """ An extension of the traditional queryset to support
        filtering on accepting_offers """

    def annotate_with_accepting_offers(self):
        """ Add a lovely little variable to the SELECT that
            says if the listing is accepting offers.

            A <thing> is accepting offers when its:
                + not cancelled
                + expire date is today or in the future
                + has spaces left
        """
        return self.annotate(accepting_offers=Q(cancelled=False) & Q(expire_date__gte=date.today()) & Q(spaces_left__gt=0))

    def accepting_offers(self):
        """ Annotate with 'accepting_offers' and filter the results that are True """
        return self.annotate_with_accepting_offers().filter(accepting_offers=True)

    def not_accepting_offers(self):
        """ Annotate with 'accepting_offers' and filter the results that are False """
        return self.annotate_with_accepting_offers().filter(accepting_offers=False)

不幸的是,这不起作用,有什么想法注释吗?

如果这是 SQL,则顶行将如下所示:

SELECT *, (cancelled=False AND expire_date >= ? AND spaces_left > 0) AS accepting_offers

编辑: 我打算进行此注释的原因是为了使对变量的过滤更容易,您可以在接下来的两个处理函数中看到这一点。

这两种方法将在更大的查询链中使用,因此(具有讽刺意味的是)使用注释保持简单应该会有所帮助。

最佳答案

正如我在评论中提到的,这根本不是 Q 表达式的用途。我想你想要的是 conditional expression :

return self.annotate(
  accepting_offers=Case(
    When(cancelled=False, expire_date__gte=date.today(), spaces_left__gt=0, then=Value(True)),
    default_value=Value(False),
    output_field=models.BooleanField()
  )
)

关于python - Django 不知何故无法确定简单的注释函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48488703/

相关文章:

python-3.x - 为什么 encode_base64 给我 TypeError : expected bytes-like object, 而不是 NoneType

python - 在Python中获取XML属性的值

python - 如何分配给 Django PointField 模型属性?

python-3.x - if 条件 + 检查 isnull() 为 true

django - 如何在 Django 中一次将多个对象添加到 ManyToMany 关系中?

python - Django 自然键不适用于固定装置?

python - 使用输入更改文件的一部分 - python

python - 如何在pyqt中更改Qtablewidget的特定单元格背景颜色

python - 为什么 `dataclasses.make_dataclass` 不将 `bytes` 转换为 `bool`

python - 使用 asyncore 创建具有客户端/服务器模型的交互式 session