python - 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)>
}
解决方案
我MultipleObjectMixin
在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
可以看出,此方法返回[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
但别担心,它们是相同的对象。
然而,奇怪的是这是未记录的功能。
推荐阅读
- node.js - 如何修复似乎无限循环的 npm?
- c# - GroupJoin 返回 Sequence 不包含任何元素
- java - @CacheEvict(...) 和 @CacheEvict(value , allEntries ) 有什么区别?
- javascript - 如何在 redux 中使用异步操作
- angular-material - Angular 7无法读取未定义的属性“地图”
- javascript - 传递唯一参数的 Java Script Pub/Sub 模式
- python - 在没有 mainloop() 的情况下更新 tkinter/matplotlib python
- jenkins - Jenkins 可扩展选择插件系统 Groovy 选择参数不起作用
- ios - 使用 Sqlite 插件时 Ionic v1 /Angular JS 慢速渲染视图
- android - OnCreateOptionsmenu 在 viewpager 中使用 tablayout 调用一次