How to sum a field of a subquery ( with OuterRef ) and annotate it on outer model?
note that I have a common my_special_queryset_annotator that alter queryset by adding some annotations, ... so i dont want to use direct Sum('books__sections__page')
let assume following models
class Library(models.Model):
votes=models.IntegerField()
class Book(models.Model):
library=models.ForiegnKey(Library)
class Section(models.Model):
book=models.ForiegnKey(Book)
pages=models.IntegerField()
# this works, but when want to use `my_special_queryset_annotator`
# we could not do this simple annotation
Library.annotate(
all_pages=Sum('books__sections__pages'),
)
# when want to sum on a Subquery, its must constructed like below but it dont work
Library.objects.annotate(
all_pages=SUM( # <-- problem
Subquery(
my_special_queryset_annotator(
Section.objects.filter(book__libraray_id=OuterRef('id'))
).values('altered_pages')
)
)
)
Sumshould be inside the subquery, as shown hereall_pages=Subquery(qs.annotate(total_pages=Sum('pages')).values('total_pages')[:1])