[英]Django ORM: How to use count method inside values_list method?
To simplify things, I need to perform this query:为了简化事情,我需要执行这个查询:
select state,count(*) from Airports group by state order by count(*) desc
And the desired return from my query is a dictionary like this:我的查询所需的返回是这样的字典:
{
'state1': value1,
'state2': value2,
'state3': value3,
...
'staten': valuen,
}
I did some research and seems I need to use aggregate and annotate but I'm kinda lost in how to perform this with values_list().我做了一些研究,似乎我需要使用聚合和注释,但我对如何使用 values_list() 执行此操作有点迷茫。
Can I use count inside it like this?我可以像这样在里面使用 count 吗?
Airport.objects.values_list('state', Airport.objects.count()).annotate('state').order_by(-Airport.objects.count())
from django.db.models import Count
Airport.objects.values('state').annotate(count=Count('state')).order_by('-count')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.