【发布时间】:2021-07-04 18:04:55
【问题描述】:
我正在尝试向我的 ListView 上下文添加一些上下文,并使用这样的 zip 在一个 for 循环中访问它们
class WeatherListView(ListView):
"""
List view of Weather data
"""
template_name = "frontend/weather_list.html"
model = Weather
def get_context_data(self, **kwargs):
weather_query = Weather.objects.all()
temp_list = list(weather_query.values_list('temperature', flat=True))
humidity_list = list(weather_query.values_list('humidity', flat=True))
temp_list_compared = compare_item_to_previous(temp_list)
humidity_list_compared = compare_item_to_previous(humidity_list)
data = super().get_context_data(**kwargs)
context = {
"object_list": zip(data, temp_list_compared, humidity_list_compared)
}
return context
然后我想在循环模板中获取我的数据
{% for i in object_list %}
{{ i.0.some_field_in_original_context }}
{{ i.1 }}
{{ i.2 }}
{% endfor %}
但我最终得到的原始上下文 {{ i.0 }} 是这样的
paginator
page_obj
is_paginated
如何在将原始 ListView 数据放入 zip 文件后仍然可以访问它。
__
更新:
知道了,我需要在原始上下文中压缩 object_list ListView 上下文如下所示:
{'paginator': None, 'page_obj': None, 'is_paginated': False,
'object_list': <QuerySet [<Weather: 2021-04-06 14:34:32.895936+00:00>,
<Weather: 2021-04-06 20:40:00.304090+00:00>,
<Weather: 2021-04-07 04:24:39.292096+00:00>]>,
'weather_list': <QuerySet [<Weather: 2021-04-06 14:34:32.895936+00:00>,
<Weather: 2021-04-06 20:40:00.304090+00:00>,
<Weather: 2021-04-07 04:24:39.292096+00:00>]>,
'view': <frontend.views.WeatherListView object at 0x7f4ec824b3d0>}
我的新上下文是:
context = {
"object_list": zip(data["object_list"], temp_list_compared, humidity_list_compared)
}
【问题讨论】:
标签: django django-templates django-template-filters