I have the following data model (the database backend is PostGres):
class User(models.Model):
...
teams = models.ManyToManyField('Team', blank=True, related_name='all_users')
...
class Team(models.Model):
...
parent_team = models.ForeignKey('self', blank=True, null=True, related_name='child_teams')
...
So a User can belong to multiple Teams, and the Teams can be nested in each other to varying degrees of depth.
I'd like to count all Users within a given team and all its children, including nested children (but exclude duplicates). Right now, I am doing it recursively, which doesn't seem like the most efficient way to go. Is there a better way to go about it?