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 AccGroup
s, then you can .annotate(…)
[Django-doc] the queryset of AccGroup
s:
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.
Source:stackexchange.com