我使用Django的通用ListView(1.9.1)。我自定义了查询集的名称(我称之为 content_list )以放入上下文中。但令人惊讶的是,当我查看上下文内容时,我可以看到 object_list 以及 content_list 。如果列表非常大,则不是很优化。如何摆脱 object_list ?以下是我的观点:
class Home(ListView): #TemplateView
context_object_name = 'content_list'
template_name = 'website/index.html'
paginate_by = CONTENT_PAGINATE_BY
def get_queryset(self):
cc_id = self.kwargs.get('cc_id')
if cc_id != None:
qs = Content.objects.filter(category=cc_id)
else:
qs = Content.objects.all()
return qs.order_by('-created_on')
def get_context_data(self, **kwargs):
context = super(Home, self).get_context_data(**kwargs)
context['content_category_list'] = ContentCategory.objects.all()
print(context)
return context
答案 0 :(得分:2)
我很确定它们都是对内存中相同列表的引用。
来自docs:
好吧,如果您正在处理模型对象,那么这已经为您完成了。当您处理对象或查询集时,Django能够使用模型类名称的较低版本填充上下文。除了默认的object_list条目之外,还提供了此功能,但包含完全相同的数据,即publisher_list。
除此之外,即使他们没有引用相同的数据,你也忘记了懒惰地执行查询集,所以如果你从不使用其他列表,那么它永远不会被执行。
答案 1 :(得分:2)
这是设计的。这不是与数据库的另一次交互,而是第二次参考。