Reputation: 3749
See my model
https://github.com/rg3915/morris/blob/master/myproject/core/models.py
How to return percent 'uf' of total?
Example:
'uf','quant'
'AM',8
'SP',9
'RJ',4
I try
p=Person.objects.values('uf').annotate(quant=Count('uf', distinct=True)).values_list('uf','quant')
print(p.query)
but return
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
and i need
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
Upvotes: 0
Views: 235
Reputation: 1829
From your example, I'm going to assume that you are looking to retrieve a list of states and the total number of people that belong to that state.
You were pretty close in your attempt, however you were lacking an order_by()
that would have let you choose the order field.
As such your query should look like this:
Person.objects.values('uf').annotate(quant=Count('uf')).order_by('uf').values_list('uf','quant')
I hope you'll notice that I have also removed the distinct=True
argument from the Count
function, as we want to be able to group all of the similar results.
Upvotes: 2