I have a problem with optimising my prefetching of a model's properties. But let's start with the code first, that makes it easier to explain my problem:
class Tournament(models.Model):
name = models.CharField(...)
@property
def active_teams(self):
return self.teams.exclude(state=TeamStateTypes.inactive)
@property
def total_count_teams(self):
return self.active_teams.count()
class Team(models.Model):
tournament = models.ForeignKey(
Tournament, ...
related_name='teams'
)
My problem is that i have multiple of these counts
like total_count_teams
. When a request retrieves a Tournament
, this leads to many SQL queries, which makes it slow.
To improve the performance i tried to prefetch
the stuff, but the SELECT COUNT(*)
queries still persist.
Tournament.objects.all().prefetch_related('teams')
Is this idea even feasible or how do I optimize/do this?