我有这个 mixin 可以在视图上应用 prefetch_related。这是我应该处理的查询集:
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)
使用我创建的这个 mixin:
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()
但是,当我尝试遍历模板中的相关对象时:
{% for p in object.projects %}
<li>{{ p.name }}</li>
{% empty %}
<li>No Projects in this Workspace</li>
{% endfor %}
我收到此错误:
'RelatedManager' object is not iterable
mixin 中是否有某些东西改变了对象以使其返回 RelatedManager?
提前致谢!