[Django]-Find Django model records that have more than one 'child' objects?

6👍

✅

You can annotate on the number of Childs and then filter on that number, like:

from django.db.models import Count

Parent.objects.annotate(
    nchild=Count('child')
).filter(nchild__gt=1)

This will generate a query like:

SELECT parent.*, COUNT(child.id) AS nchild
FROM parent
LEFT OUTER JOIN child ON parent.id = child.parent_id
GROUP BY parent.id
HAVING COUNT(child.id) > 1

One can change the .filter(..) condition to all sorts of conditions on the number of childs nchilds, for example nchild=4 filters on Parents with exactly four children, whereas ~Q(nchild=7) will exclude all Parents with exactly seven children. We can thus make more complicated filters.

Leave a comment