Django 条件注释
我很惊讶这个问题显然还不存在。如果有的话,请帮我找到它。
我想使用 annotate (Count) 和 order_by,但我不想计算相关对象的每个实例,只计算那些满足特定条件的实例。
也就是说,我可以根据燕子携带的绿色椰子的数量来列出它们:
swallow.objects.annotate(num_coconuts=Count('coconuts_carried__husk__color = "green"').order_by('num_coconuts')
I'm surprised that this question apparently doesn't yet exist. If it does, please help me find it.
I want to use annotate (Count) and order_by, but I don't want to count every instance of a related object, only those that meet a certain criteron.
To wit, that I might list swallows by the number of green coconuts they have carried:
swallow.objects.annotate(num_coconuts=Count('coconuts_carried__husk__color = "green"').order_by('num_coconuts')
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对于 Django >= 1.8:
For Django >= 1.8:
这应该是正确的方法。
请注意,当您过滤相关字段时,在原始 SQL 中,它会转换为 LEFT JOIN 加 WHERE。最后,注释将作用于结果集,该结果集仅包含从第一个过滤器中选择的相关行。
This should be the right way.
Note that when you filter for a related field, in raw SQL it translates as a LEFT JOIN plus a WHERE. In the end the annotation will act on the result set, which contains only the related rows which are selected from the first filter.