问题
My Models looks like:
class Book(models.Model):
publisher = models.ForeignKey(Publisher) # This is not important
class Baz(models.Model):
a = models.CharField(max_length=100)
class Page(models.Model):
book = models.ForeignKey(Book)
baz = models.ForeignKey(Baz)
And I am trying to run a query like this:
[[x.baz.a for x in y.page_set.all()]
for y in Book.objects.all().prefetch_related('page_set', 'page_set__baz')]
Which I think the ORM should be able to perform as two queries: (Page JOIN Baz
) and Book
. The final join should occur in Python. Instead I see the ORM executing three queries. I believe that I have to some how use select_related
, but this does not work either (nor does moving select_related
before prefetch_related
):
Book.objects.all().prefetch_related('page_set', 'page_set__baz').select_related('page_set__baz')
The queries (uploads
is the app):
QUERY = u'SELECT "uploads_book"."id", "uploads_book"."publisher_id" FROM "uploads_book"' - PARAMS = (); args=()
QUERY = u'SELECT "uploads_page"."id", "uploads_page"."book_id", "uploads_page"."baz_id" FROM "uploads_page" WHERE "uploads_page"."book_id" IN (%s, %s)' - PARAMS = (1, 2); args=(1, 2)
QUERY = u'SELECT "uploads_baz"."id", "uploads_baz"."a" FROM "uploads_baz" WHERE "uploads_baz"."id" IN (%s)' - PARAMS = (1,); args=(1,)
This is related to the comment here: prefetch_related for multiple Levels
回答1:
You can try to use Prefetch object
page_qs = Page.objects.select_related('baz')
books = Book.objects.prefetch_related(Prefetch('page_set', queryset=page_qs))
来源:https://stackoverflow.com/questions/27121331/select-related-after-prefetch-related