Search code examples
djangodjango-generic-views

Django generic ListView: duplicate queryset in the context


I'm using the generic ListView of Django (1.9.1). I customized the name of the queryset (I called it content_list) to be put in the context. But surprisingly when I look at the context content, I can see object_list along with content_list. If the list is very big this is not very optimised. How can I get rid of object_list?. Here is my view:

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

Solution

  • I'm pretty sure they're both reference to the same list in memory.

    From the 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.

    Aside from that, even if they weren't referencing the same data, you're forgetting that querysets are executed lazily so if you never use the other list then it is never executed.