首页 > 解决方案 > ListView 的上下文中有 2 个相同的查询集

问题描述

我想知道为什么上下文中有 2 个相同的查询集:object_list 和 Massage_list。我做错什么了吗?我只能在网址中找到按摩列表path('work/', MassageListView.as_view(), name='massage_list')

class MassageListView(ListView):
    def get_queryset(self):
        return Massage.objects.filter(time_of_receipt__year=now().year,
                                   time_of_receipt__month=now().month)

    def get_context_data(self, *, object_list=None, **kwargs):
        context = super(MassageListView, self).get_context_data(**kwargs)
        month_salary = 0
        for i in context['object_list']:
            month_salary += i.price
        context['month_salary'] = month_salary
        context['form'] = MassageForm()
        print(context)
        return context

印刷上下文

{
  'paginator': None, 
  'page_obj': None, 
  'is_paginated': False, 
  'object_list': <QuerySet [<Massage: 2021-08-11 12:00:00+00:00>, <Massage: 2021-08-14 12:00:00+00:00>]>, 
  'massage_list': <QuerySet [<Massage: 2021-08-11 12:00:00+00:00>, <Massage: 2021-08-14 12:00:00+00:00>]>, 
  'view': <myapp.views.MassageListView object at 0x7f2e166200a0>, 
  'month_salary': 13800, 
  'form': <MassageForm bound=False, valid=Unknown, fields=(client;price;count;time_of_receipt)>
}

标签: pythondjango

解决方案


MultipleObjectMixinBaseListView.

    def get_context_object_name(self, object_list):
        """Get the name of the item to be used in the context."""
        if self.context_object_name:
            return self.context_object_name
        elif hasattr(object_list, 'model'):
            return '%s_list' % object_list.model._meta.model_name
        else:
            return None

可以看出,此方法返回[model_name]_list字符串,稍后在get_context_data方法中与 with 一起使用object_list

    def get_context_data(self, *, object_list=None, **kwargs):
        """Get the context for this view."""
        queryset = object_list if object_list is not None else self.object_list

        ...       

        context_object_name = self.get_context_object_name(queryset)

        ...   

        if context_object_name is not None:
            context[context_object_name] = queryset

        ...   

        return context

但别担心,它们是相同的对象。

然而,奇怪的是这是未记录的功能。


推荐阅读