gpt4 book ai didi

Django通用ListView : duplicate queryset in the context

转载 作者:行者123 更新时间:2023-12-02 04:13:30 25 4
gpt4 key购买 nike

我正在使用 Django (1.9.1) 的通用 ListView。我自定义了要放入上下文中的查询集的名称(我将其称为 content_list)。但令人惊讶的是,当我查看上下文内容时,我可以看到 object_listcontent_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

最佳答案

我很确定它们都引用了内存中的同一个列表。

来自docs :

Well, if you’re dealing with a model object, this is already done for you. When you are dealing with an object or queryset, Django is able to populate the context using the lower cased version of the model class’ name. This is provided in addition to the default object_list entry, but contains exactly the same data, i.e. publisher_list.

除此之外,即使它们没有引用相同的数据,您也会忘记查询集是延迟执行的,因此如果您从不使用其他列表,那么它就永远不会执行。

关于Django通用ListView : duplicate queryset in the context,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35220326/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com