Django Model Group

I have a simple SQL query -

SELECT pid, COUNT(*) AS docs FROM xml_table WHERE suid='2' GROUP BY pid;

How to get this using Django ORM (e.g. django models). Basically, I don’t understand how to do this GROUP BY?

+2
source share
2 answers

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

Docs

+6
source

It works very well.

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

This is not SQL. This is often faster than SQL because it does not impose sorting on a large table or the result of a join.

+1
source

Source: https://habr.com/ru/post/1736752/


All Articles