Django ORM:如何在 values_list 方法中使用计数方法?
Django ORM: How to use count method inside values_list method?
为了简化事情,我需要执行这个查询:
select state,count(*) from Airports group by state order by count(*) desc
我的查询中所需的 return 是这样的字典:
{
'state1': value1,
'state2': value2,
'state3': value3,
...
'staten': valuen,
}
我做了一些研究,似乎我需要使用聚合和注释,但我有点不知道如何使用 values_list() 执行此操作。
我可以像这样在里面使用计数吗?
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')
为了简化事情,我需要执行这个查询:
select state,count(*) from Airports group by state order by count(*) desc
我的查询中所需的 return 是这样的字典:
{
'state1': value1,
'state2': value2,
'state3': value3,
...
'staten': valuen,
}
我做了一些研究,似乎我需要使用聚合和注释,但我有点不知道如何使用 values_list() 执行此操作。
我可以像这样在里面使用计数吗?
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')