selectflated在prefetch_related之后

时间:2014-11-25 07:54:19

标签: django django-queryset django-orm

我的模特看起来像:

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)

我正在尝试运行这样的查询:

[[x.baz.a for x in y.page_set.all()]
for y in Book.objects.all().prefetch_related('page_set', 'page_set__baz')]

我认为ORM应该能够作为两个查询执行:(Page JOIN Baz)和Book。最终的连接应该在Python中进行。相反,我看到ORM执行三个查询。我相信我必须使用select_related,但这也不起作用(也不会在select_related之前移动prefetch_related):

Book.objects.all().prefetch_related('page_set', 'page_set__baz').select_related('page_set__baz')

查询(uploads是应用):

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,)

这与此处的评论有关:prefetch_related for multiple Levels

1 个答案:

答案 0 :(得分:3)

您可以尝试使用Prefetch object

page_qs = Page.objects.select_related('baz')
books = Book.objects.prefetch_related(Prefetch('page_set', queryset=page_qs))