0

我有这个 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?

提前致谢!

4

2 回答 2

2

@danihp 有它:你需要.all.

这里还有一个错误:

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

应该读

return queryset.prefetch_related(*self.prefetch_related)

prefetch_related接受多个字符串参数,而不是单个逗号分隔的字符串。

于 2012-10-26T17:49:02.590 回答
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 %}
于 2012-10-26T11:45:10.223 回答