Django条件注释 [英] Django conditional annotation

查看:133
本文介绍了Django条件注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很惊讶,这个问题显然还不存在。如果是这样,请帮我找到它。



我想使用annotate(Count)和order_by,但是我不想计数每个相关对象的实例只有那些符合某些标准的人才可以。



我可以按照他们携带的绿色椰子的数量列出燕子:

  swallow.objects.annotate(num_coconuts = Count('coconututs_carried__husk__color =green')。order_by('num_coconuts')


解决方案

这应该是正确的方式。

  swallow.objects.filter(
coconututs_carried__husk__color =green
).annotate(
num_coconuts = Count('coconututs_carried')
).order_by('num_coconuts')

请注意,当您过滤相关字段时,在原始SQL它转换为LEFT JOIN加上WHERE。最后,注释将作用于结果集,其中仅包含所选的相关行从第一个过滤器。


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')

解决方案

This should be the right way.

swallow.objects.filter(
    coconuts_carried__husk__color="green"
).annotate(
    num_coconuts=Count('coconuts_carried')
).order_by('num_coconuts')

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.

这篇关于Django条件注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆