Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 #?!?
like image 405
apelliciari Avatar asked Mar 03 '13 16:03

apelliciari


People also ask

How do you get a related name on Django?

The related_name attribute specifies the name of the reverse relation from the User model back to your model. If you don't specify a related_name, Django automatically creates one using the name of your model with the suffix _set.

What does ForeignKey mean in Django?

What is ForeignKey in Django? ForeignKey is a Field (which represents a column in a database table), and it's used to create many-to-one relationships within tables. It's a standard practice in relational databases to connect data using ForeignKeys.

What's the difference between Django OneToOneField and ForeignKey?

The only difference between these two is that ForeignKey field consists of on_delete option along with a model's class because it's used for many-to-one relationships while on the other hand, the OneToOneField, only carries out a one-to-one relationship and requires only the model's class.

What is Django's ORM?

One of the most powerful features of Django is its Object-Relational Mapper (ORM), which enables you to interact with your database, like you would with SQL. In fact, Django's ORM is just a pythonical way to create SQL to query and manipulate your database and get results in a pythonic fashion.


2 Answers

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)
like image 190
Daniel Roseman Avatar answered Oct 11 '22 05:10

Daniel Roseman


When you query cross models, double underscores may help

book = Book.objects.get(pk=1)
pages = Page.objects.filter(chapter__book=book)
like image 26
iMom0 Avatar answered Oct 11 '22 06:10

iMom0