Django: get related set from a related set of a mo

2019-06-17 03:49发布

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 #?!?

2条回答
叼着烟拽天下
2楼-- · 2019-06-17 04:05

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)
查看更多
唯我独甜
3楼-- · 2019-06-17 04:15

When you query cross models, double underscores may help

book = Book.objects.get(pk=1)
pages = Page.objects.filter(chapter__book=book)
查看更多
登录 后发表回答