簡體   English   中英

Django ORM:如何在 values_list 方法中使用 count 方法?

[英]Django ORM: How to use count method inside values_list method?

為了簡化事情,我需要執行這個查詢:

 select state,count(*) from Airports group by state order by count(*) desc

我的查詢所需的返回是這樣的字典:

{
 'state1': value1,
 'state2': value2,
 'state3': value3,
        ...
 'staten': valuen,
}

我做了一些研究,似乎我需要使用聚合和注釋,但我對如何使用 values_list() 執行此操作有點迷茫。

我可以像這樣在里面使用 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM