首页 > 解决方案 > 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

如果我切换它们,则将第二个循环放在第一位,它将起作用,而另一个则不会。

标签: djangodjango-viewsdjango-templates

解决方案


推荐阅读