[Answered ]-Django model has foreignkey to self. I want to get count of children?

1👍

You can count the direct children with:

myaccgroup.accgroup_set.count()

this will thus not take into account grand children, etc. Only the items tat are one layer below the myaccgroup object.

If you need this for a large number of AccGroups, then you can .annotate(…) [Django-doc] the queryset of AccGroups:

from django.db.models import Count

AccGroup.objects.annotate(
    nchildren=Count('accgroup')
)

The AccGroup objects that arise from this querysete will have an extra attribute .nchildren that thus for each AccGroup will carry the number of direct children.

Leave a comment