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

南笙酒味 提交于 2020-01-03 08:43:27

问题


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

回答1:


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)



回答2:


When you query cross models, double underscores may help

book = Book.objects.get(pk=1)
pages = Page.objects.filter(chapter__book=book)


来源:https://stackoverflow.com/questions/15187845/django-get-related-set-from-a-related-set-of-a-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!