Tzach
Tzach

Reputation: 13376

Django: Reducing number of queries when filtering by foreign key

I have the following code:

class Book(models.Model):
    author = models.ForeignKey(Author)

    def get_books_for_same_author(self):
        return Book.objects.filter(author = self.author)

When calling get_books_for_same_author, my common sense tells me that 2 DB queries are issued - one to get self.author and another for getting the books for this author.

Am I right? If so, is there a way to get the same results with only one query?

Upvotes: 0

Views: 55

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599610

Yes, that would involve two queries, if you have not already fetched self.author for that instance either by accessing it directly, or by using select_related when you originally fetched the book.

However you don't actually need the author object at all here: the book model directly contains an underlying author_id field which you can use instead:

return Book.objects.filter(author=self.author_id)

and this will only incur one query.

Upvotes: 2

Related Questions