Search code examples
djangodjango-modelsdjango-templatesdjango-tables2

Django model has foreignkey to self. I want to get count of children?


I have a model as below which is hierarchical Group The group has either a parent group or none

class AccGroup(models.Model):
    grpid = models.BigAutoField(primary_key=True, editable=False)
    groupname = models.CharField(max_length=40, default="", verbose_name='Group Name')
    parentgrpid = models.ForeignKey('self',on_delete= models.SET_NULL,  blank=True, null=True, verbose_name='Parent Group')
    printlevel = models.IntegerField(default=0, verbose_name='Print Level')
    def __str__(self):
        return "%s" % (self.groupname)

This group list is displayed in HTML Table using a template by sending a querylist as context

 
<table>
    <thead>
        <th>Group Name</th><th>Parent Group</th><th>Print Level</th><th>Children</th>
    </thead>
    <tbody>
     {% for group in grouplist %}                        
        <tr>
            <td><a  href="{% url 'groupupdate' menu.grpid %}" >                       
            {{group.groupname}}</a>
            </td>
            <td>{{group.parentgrpid}}</td> <td>{{group.printlevel}}</td> <td>{{group.accgroup__count}}</td>
        </tr>
        {% endfor %}                      
    </tbody>
</table>

If there are child groups then I want to know how many child groups are under the group which I can print in html table How to get children group count from parent group object


Solution

  • 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.