How to prefetch aggregated @property in Django?

We have two models (simplified versions):

class Contestant(models.Model):
    email = models.EmailField(max_length=255, unique=True)
    # plus some other fields

    @property
    def total_points(self):
        return self.points.aggregate(total=Sum('value'))['total'] or 0

class Points(models.Model):
    contestant = models.ForeignKey(Contestant, related_name='points')
    value = models.PositiveIntegerField()
    # plus some other fields which determine based on what we
    # awarded ``Points.value``

When we show the list of participants along with the value total_points, this leads to an additional query for each result - i.e. The following queries are executed:

  • list of selected members.
  • fetch total_pointsvalue of the first member
  • fetch total_pointsvalue of the second member
  • etc.

I tried to modify the query set for prefetching data as follows:

Contestant.objects.filter(...).prefetch_related('points')

... though, although it works, the preselected data is not used when (therefore, each result is still trying to get total_points in a separate request).

Is it possible:

  • - ORM @property, (, Contestant.total_points @property)?
  • - ( )?
  • ?

( tastypie, .)

.

+3
1

, , annotate aggregate.

( , ):

Contestant.objects.filter(...).annotate(total_points=Sum('points__value'))

: , - . . - QuerySet,

+9

Source: https://habr.com/ru/post/1568889/


All Articles