我正在尝试在查询集类上创建一个注释,该注释仅添加一个 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/