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.
精彩评论