Django ListView如何使用其他上下文压缩上下文数据 [英] Django ListView how to zip context data with another context
问题描述
我正在尝试向ListView上下文中添加一些上下文,并使用这样的zip在一个for循环中访问它们
I'm trying to add some context to my ListView context and access them in one for loop with zip like this
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
然后我想在循环模板中获取数据
Then I want to get my data in the template for loop
{% for i in object_list %}
{{ i.0.some_field_in_original_context }}
{{ i.1 }}
{{ i.2 }}
{% endfor %}
但是对于我的原始上下文{{i.0}},我最终得到的是这个
But what I end up having for my original context {{ i.0 }} is this
paginator
page_obj
is_paginated
将我的ListView数据放入zip文件后,如何仍然可以访问它.
How can I still access my original ListView data after putting it in a zip.
__
更新:
我需要将object_list压缩到原始上下文ListView上下文中,如下所示:
Got it I needed to zip object_list inside the original context ListView context looks like this:
{'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)
}
推荐答案
我需要将object_list压缩到原始上下文ListView上下文中,如下所示:
Got it I needed to zip object_list inside the original context ListView context looks like this:
{'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 ListView如何使用其他上下文压缩上下文数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!