Reputation: 47
I am wondering why there are 2 same querysets in the context: object_list and massage_list. Did I do something wrong? I could find massage_list only in urls 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
printed 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)>
}
Upvotes: 0
Views: 82
Reputation: 2483
I found this method in the MultipleObjectMixin
which is inherited by BaseListView
.
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
This method as can be seen returns [model_name]_list
string, which is later used in the get_context_data
method alongside 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
But don't worry, it's the same objects.
However it's weird that this is undocumented feature.
Upvotes: 1