2014-11-25 68 views
0

我的模型看起來像:select_related prefetch_related後

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,但這並不工作,要麼(也不prefetch_related前移動select_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

回答

2

你可以嘗試使用Prefetch object

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