我有這個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?
在此先感謝!
如果給定相同的模型/視圖上下文,這將如何與ManyToMany關係一起工作? –