2

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?

mrehan
  • 1,122
  • 9
  • 18
Berni
  • 238
  • 4
  • 10

1 Answers1

4

I actually was able to prevent the SELECT COUNT(*) queries by using @cached_property from django.utils.functional instead of @property

This caches the relevant properties and is not making unnecessary database queries. Paired with a normal prefetching of teams my performance is now drastically improved.

Berni
  • 238
  • 4
  • 10