Search code examples
djangoormmodelsaggregatedjango-queryset

In Django how can i get aggregated data on more than two models


class Book(models.Model):
    # fields

class Chapter(models.Model):
     book = models.ForeignKey(Book)

class Page(models.Model):
     chapter = models.ForeignKey(Chapter)

If i want to know the number of pages in that specific book 'A', what is the best way to achieve this?

Of course i can cycle on chapters of Book A and sum the pages of each chapters, but i don't think is the smarter way.

Is there a way to do this through the ORM / Queryset? Some kind of aggregation?


Solution

  • Something like this could work:

    book_a = Book.objects.get(name='A')
    page_count = Page.objects.filter(chapter__book=book_a).count()
    

    This will result in a database join, which will return the count of pages whose chapter is from book A.