How to aggregate annotate fields of related models in django
My problem is a little more complicated, but I'm posting the question in the simplest possible way.
- Annotated
total_score
inPhoto
. - I would like to annotate
max_total_score
inPerson
.
I wrote get_queryset
of PersonManager
, but the following error occurred.
Is there a new way?
models.py
from django.db import models
class PersonManager(models.Manager):
def get_queryset(self):
photos_prefetch = models.Prefetch(
'photos',
Photo.objects.annotate(total_score=models.Sum('features__score'))
)
return super().get_queryset() \
.prefetch_related(photos_prefetch) \
.annotate(max_total_score=models.Max('photos__total_score'))
class Person(models.Model):
objects = PersonManager()
class Photo(models.Model):
person = models.ForeignKey(Person, models.CASCADE, related_name='photos')
class Feature(models.Model):
photo = models.ForeignKey(Photo, models.CASCADE, related_name='features')
name = models.CharField(max_length=100)
score = models.IntegerField()
shell
>> Person.objects.all()
# Unsupported lookup 'total_score' for BigAutoField or join on the field not permitted