开发者

Django Models Group By

开发者 https://www.devze.com 2023-03-03 22:32 出处:网络
I have this simple SQL query - SELECT pid, COUNT(*) AS docs FROM xml_table WHERE suid=\'2\' GROUP BY pid;开发者_如何学C

I have this simple SQL query -

SELECT pid, COUNT(*) AS docs FROM xml_table WHERE suid='2' GROUP BY pid;开发者_如何学C

How do I get this using Django ORM (i.e. django models). Basically I am not getting how to do GROUP BY?


XML_table.objects.filter(suid='2').values('pid').annotate(docs=Count('pid')).order_by()

Docs


This works very nicely.

from collections import defaultdict
count = defaultdict( int )
for doc in XML_Table.objects.filter(suid='2'):
    count[doc.pid] += 1

It's not SQL. Often it's faster than SQL because it doesn't impose a sort on a large table or join result.

0

精彩评论

暂无评论...
验证码 换一张
取 消