python - 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()
))
)
不幸的是,这会返回一个空的查询集。删除条件会正常返回一个查询集,但最后一个注释似乎会破坏查询。
怎么了?
解决方案
推荐阅读
- java - 我们如何在 Android 应用程序中创建 Kafka 生产者?
- c# - Dotnet Core Windows 服务中的多个托管服务
- r - R中所有列的相同循环以创建新数据框
- python - 需要在网页中集成 Python 解释器,该网页将代码发布到执行它的服务器
- postgresql - 如何根据其他参数仅在某些记录上过滤表?
- rust - 为什么修改可变借用变量并保持其未使用不会引发错误
- apache-spark - apache spark phoenix 连接器不支持流式读取
- ibm-mobilefirst - WKWebViewEngine 仅在与 cordova-plugin-mfp 结合使用时显示空白屏幕
- python - Tkinter 比例和动画不会运行
- javascript - 如何在 v-for 中使用 if 语句?