9
class Book(models.Model):
    # fields

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

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

I want all the pages of the book A, possibly without cycling every chapter to fetch the pages.

book = Book.objects.get(pk=1)
pages = book.chapter_set.page_set #?!?
tshepang
  • 12,111
  • 21
  • 91
  • 136
apelliciari
  • 8,241
  • 9
  • 57
  • 92

2 Answers2

10

You can't do it that way. chapter_set is a query set, it doesn't have an attribute page_set.

Instead, turn it around:

Page.objects.filter(chapter__book=my_book)
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
4

When you query cross models, double underscores may help

book = Book.objects.get(pk=1)
pages = Page.objects.filter(chapter__book=book)
iMom0
  • 12,493
  • 3
  • 49
  • 61