2012-10-26 62 views
0

我有這個mixin在視圖上應用prefetch_related。這是我應該是工作的查詢集:Django prefetch_related在通用視圖DetailView

MyMode.objects.all().prefetch_related('projects') 

有這些模特:

class Workspace(): 
name = models.CharField(max_length=255) 
class Project(): 
name = models.CharField(max_length=255) 
workspace = models.Foreignkey(Workspace) 

與此混入我創建:

class PrefetchRelatedMixin(object): 
    prefetch_related = None 

    def get_queryset(self): 
     if self.prefetch_related is None: 
      raise ImproperlyConfigured(u'%(cls)s is missing the prefetch_related' 
       "property. This must be a tuple or list." % { 
       'cls': self.__class__.__name__}) 

     if not isinstance(self.prefetch_related, (tuple, list)): 
      raise ImproperlyConfigured(u"%(cls)s's select_related property " 
       "must be a tuple or list." % {"cls": self.__class__.__name__}) 

     queryset = super(PrefetchRelatedMixin, self).get_queryset() 

     return queryset.prefetch_related(
      ", ".join(self.prefetch_related) 
     ) 

叫這樣的觀點:

class WorkspaceView(DetailView): 
    prefetch_related = ['projects'] 
    model = Workspace 

    def get_queryset(self): 
     return super(WorkspaceView, self).get_queryset() 

H H但是,當我嘗試遍歷相關對象在我的模板:

{% for p in object.projects %} 
    <li>{{ p.name }}</li> 
{% empty %} 
    <li>No Projects in this Workspace</li> 
{% endfor %} 

我得到這個錯誤:

'RelatedManager' object is not iterable 

有什麼在改變了對象上,要返回的混入RelatedManager?

在此先感謝!

回答

1

prefetch_related是RelatedManager,您應該執行方法得到的結果:

在文檔樣本:

>>> pizzas = Pizza.objects.prefetch_related('toppings') 
>>> [list(pizza.toppings.filter(spicy=True)) for pizza in pizzas] 

對於您的情況:

{% for p in object.projects.all %} 
+0

如果給定相同的模型/視圖上下文,這將如何與ManyToMany關係一起工作? –

1

@danihp有它:你需要.all

還有這裏的錯誤:

return queryset.prefetch_related(
      ", ".join(self.prefetch_related) 
     ) 

應改爲

return queryset.prefetch_related(*self.prefetch_related) 

prefetch_related需要多個字符串參數,而不是一個逗號分隔的字符串。