0

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.