首页 > 解决方案 > Django 1.8 条件表达式返回空查询集

问题描述

我有两个类似这样的模型:

class Foo(models.Model):
    # fields...

class Bar(models.Model):
    foo = models.ForeignKey(Foo)
    is_done = models.BooleanField()
    # more fields....

我想Foo用所有相关Bar对象的计数来注释,这些对象is_done是真的。

不幸的是,我被困在 Django 1.8 中,所以Count('bar', filter='bar__is_done) 对我来说不是一个选择。

因此,我使用了条件聚合:

Foo.objects.all().annotate(
    # other fields...
    done=Count(Case(
        When(bar__is_done=True, then=1),
        output_field=IntegerField()
    ))
)

不幸的是,这会返回一个空的查询集。删除条件会正常返回一个查询集,但最后一个注释似乎会破坏查询。

怎么了?

标签: pythondjangodjango-models

解决方案


推荐阅读