2015-05-02 58 views
0

見我的模型標註在一個模型的Django

https://github.com/rg3915/morris/blob/master/myproject/core/models.py

如何返回%的總的「用友」?

實施例:

'UF', '定量'

'AM',8

'SP',9

'RJ',4

我嘗試

p=Person.objects.values('uf').annotate(quant=Count('uf', distinct=True)).values_list('uf','quant') 
print(p.query) 

但是返回

SELECT "core_person"."uf", COUNT(DISTINCT "core_person"."uf") AS "quant" FROM "core_person" GROUP BY "core_person"."uf", "core_person"."first_name" ORDER BY "core_person"."first_name" ASC 

,我需要

SELECT "core_person"."uf", COUNT(DISTINCT "core_person"."uf") AS "quant" FROM "core_person" GROUP BY "core_person"."uf" ORDER BY "core_person"."uf" ASC 

回答

2

從你的榜樣,我會假設你正在尋找檢索國家的列表和屬於該國的總人數。

您的嘗試非常接近,但您缺少可讓您選擇訂單字段的order_by()

這樣您的查詢應該是這樣的:

Person.objects.values('uf').annotate(quant=Count('uf')).order_by('uf').values_list('uf','quant') 

我希望你會發現,我還移除了Count功能distinct=True說法,因爲我們希望能夠將所有的類似的結果。

+0

我來得非常接近它。謝謝。 –

+0

嗨,但是返回 [('AC',10),('AL',9),('AM',8),('AP',8),('BA',11) 如何返回 [(uf:'AC',quant:10),(uf:'AL',quant:9),(uf:'AM',quant:8),(uf:'AP ',quant:8),(uf:'BA',quant:11),... –

+1

已解決:Person.objects.values('uf')。annotate(quant = Count('uf'))。order_by 'uf')。values('uf','quant') –