sebtheiler
sebtheiler

Reputation: 2557

Get all Foreign Keys of a Foreign Key in Django

For example,

If there was a model Bookshelf which had a foreign key to a model Books that was accesible by bookshelf.books, and the Book model has a foreign key Author (accesible through book.authors), how would I get all the authors from a Bookshelf?

Example models.py

class Bookshelf(models.Model):
    pass

class Book(models.Model):
    bookshelf = models.ForeignKey(Bookshelf, related_name='books', on_delete=models.CASCADE)

class Author(models.Model):
    book = models.ForeignKey(Book, related_name='authors', on_delete=models.CASCADE)

I could do:

author_qs = QuerySet(Author)
for book in my_bookshelf.books.all():
    author_qs |= book.authors.all()

But I doubt this is very efficient.

Any help is much appreciated. (If it matters, I'm using Postgres)

Upvotes: 0

Views: 1909

Answers (2)

Biplove Lamichhane
Biplove Lamichhane

Reputation: 4095

"To span a relationship, use the field name of related fields across models, separated by double underscores, until you get to the field you want." - django-docs

So you can do:

queryset = Author.objects.filter(book__bookshelf=bookshelf)

Upvotes: 2

Attila Viniczai
Attila Viniczai

Reputation: 693

I believe a solution can be found in this answer: https://stackoverflow.com/a/37515546/14349691

The above answer is also very detailed.

Upvotes: 0

Related Questions