Django queryset annotate sum of related objects of related objects

У меня есть

class Book(models.Model):
    title = models.CharField(max_length=32)

class Table(models.Model):
    book = models.ForeignKey(Book, related_name='tables')

class TableEntry(models.Model):
    table = models.ForeignKey(Table, related_name='entries')
    value = models.FloatField()

и хотим получить набор книг, в котором для каждой книги есть аннотация, сумма всех записей в таблице этой книги.

Я пытался

Book.objects.all().annotate(sum=Sum('tables__entries'))

но, похоже, это не работает.

Обратите внимание, что эта идея работает, когда сумма всех записей каждой таблицы должна быть аннотирована:

Table.objects.all().annotate(sum=Sum('entries'))

You can annotate the prefetched Tables, like:

from django.db.models import Prefetch, Sum

Book.objects.prefetch_related(
    Prefetch('tables', Table.objects.annotate(sum=Sum('entries__value')))
)

If you then access a Book instance (named book for example), the book.tables.all() is a QuerySet of Tables with each an extra sum attribute that is the sum of value of the entries of the Table.

Вернуться на верх