how to get count of each distinct value

25 views
Skip to first unread message

Fatih Tiryakioglu

unread,
Nov 22, 2013, 10:44:19 AM11/22/13
to django...@googlegroups.com
Hi all,

How can I get distribution of values in a field? For example, I have the scores below:

             (score)
(raw1)        1
(raw2)        1
(raw3)        3
(raw4)        4
(raw5)        4
(raw6)        5
(raw7)        8
(raw8)        8
(raw9)        9
(raw10)    10

I want to have a result like that: {1: 2}, {3: 1}, {4: 2}, {5: 1}, {8: 2}, {9: 1}, {10: 1}. So it is {score: count}.

How can I evaluate this only one db hit?

Thanks all.


--

Larry Martell

unread,
Nov 22, 2013, 11:07:47 AM11/22/13
to django...@googlegroups.com
In SQL:

SELECT score, COUNT(*) FROM foo GROUP BY score; 

In Django:

from django.db.models import Count
q = Foo.objects.values('score').annotate(Count('score'))
for r in q:
    print r, r.score__count

Fatih Tiryakioglu

unread,
Nov 22, 2013, 2:51:39 PM11/22/13
to django...@googlegroups.com
Thank you.


--

22 Kasım 2013 Cuma 18:07:47 UTC+2 tarihinde Larry....@gmail.com yazdı:
Reply all
Reply to author
Forward
0 new messages