django - Django 模板只出现第一个循环
问题描述
我想向 ListView 上下文添加一些自定义上下文,如下所示:
def compare_item_to_previous(list):
"""
compares a list items with the ones before them
and returns a list of 0, 1 and 2. 1 means greater
than, 2 means less than and 0 means equal.
"""
compared_list = []
prev_index = list[0]
for i in list:
if i > prev_index:
compared_list.append(1)
elif i < prev_index:
compared_list.append(2)
else:
compared_list.append(0)
prev_index = i
return compared_list
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["object_list"], temp_list_compared, humidity_list_compared)
}
print("context ", context)
return context
我的模型.py
class Weather(models.Model):
temperature = models.FloatField(
validators=[MaxValueValidator(28), MinValueValidator(19)]
)
humidity = models.FloatField(
validators=[MaxValueValidator(65), MinValueValidator(35)]
)
time_recorded = models.DateTimeField(auto_now_add=True, blank=True)
但是当我尝试在模板中循环它们时,只有第一个循环像这样工作:
{% for i in object_list %}
{{ i.0.temperature }}
{{ i.1 }}
{% endfor %}
{% for i in object_list %}
{{ i.0.humidity }}
{{ i.2 }}
{% endfor %}
预期的结果是
11.0 12.0 13.0 0 1 1 20.0 22.0 23.0 0 1 1
但我得到的是:
11.0 12.0 13.0 0 1 1
如果我切换它们,则将第二个循环放在第一位,它将起作用,而另一个则不会。
解决方案
推荐阅读
- hibernate - Spring Data JPA - 如何在同一列上使用多个值实现 LIKE 搜索
- snakemake - 来自多个目录的 Snakemake 副本
- java - 使用 randomAccessFileOrArray()
- c - 制作操作系统时可以使用库吗
- c++ - 我想通过 OpenGL 创建 3D 金字塔
- python-3.x - sorted 如何处理正值和负值?
- python - Sphinx - 让自定义 HTML 知道变量
- python - 以空值可能性启动python if函数
- javascript - 在新选项卡中打开超链接并运行 php 函数
- python - 检查输入是否等于特定字符串而不重复代码