从Flask迁移到Django:模板并行遍历列表字典的问题
从Flask迁移到Django:多关联列表并行遍历问题解决
在将个人项目从Flask迁移到Django时,核心障碍是无法在Django模板中像Flask的Jinja模板那样通过索引并行遍历多个关联列表。
Flask原实现
在Flask的Jinja模板中,可通过loop.index0获取循环索引,以此关联多个列表的对应元素:
{% for item in time_period %} <div class="col-lg-3 col-sm-4"> <div class="card h-100 border border-dark rounded"> <img class="card-image" src={{temp_icon[loop.index0]}}> </img> <div class="card-body"> <h2>{{item}}, {{temperature[loop.index0]}} F</h2> <p class="card-text">{{forecast[loop.index0]}}</p> </div> </div> </div> {% endfor %}
Django视图代码
当前Django视图中,weather()返回的四个变量均为列表,直接传入模板上下文:
def forecast(request): # 调用weather.py获取NWS定义的未来时段天气预报 time_period, temperature, forecast, temp_icon = weather() context = { 'time_period': time_period, 'temperature': temperature, 'forecast': forecast, 'temp_icon': temp_icon } print(context) return render(request, "forecast.html", context)
示例数据
上下文包含的示例列表数据如下:
{ 'time_period': ['This Afternoon', 'Tonight', 'Friday', 'Friday Night'], 'temperature': [88, 70, 95, 72], 'forecast': ['Partly Sunny', 'Slight Chance Showers And Thunderstorms', 'Chance Showers And Thunderstorms', 'Chance Showers And Thunderstorms'], 'temp_icon': ['https://api.weather.gov/icons/land/day/bkn?size=medium', 'https://api.weather.gov/icons/land/night/tsra_hi,20?size=medium', 'https://api.weather.gov/icons/land/day/rain_showers,20/tsra_hi,40?size=medium', 'https://api.weather.gov/icons/land/night/tsra_hi,30?size=medium'] }
解决方案:重构数据为嵌套字典
尝试修改上下文结构、使用计数器、压缩列表等方法均未成功,最终通过将分散的列表重构为嵌套字典解决问题:
重构后的数据结构
{ 0: {'time_period': 'This Afternoon', 'temperature': 88, 'forecast': 'Partly Sunny', 'temp_icon': 'https://api.weather.gov/icons/land/day/bkn?size=medium'}, 1: {'time_period': 'Tonight', 'temperature': 70, 'forecast': 'Slight Chance Rain Showers', 'temp_icon': 'https://api.weather.gov/icons/land/night/rain_showers,20?size=medium'}, 2: {'time_period': 'Friday', 'temperature': 94, 'forecast': 'Partly Sunny then Chance Showers And Thunderstorms', 'temp_icon': 'https://api.weather.gov/icons/land/day/bkn/tsra_hi,40?size=medium'}, 3: {'time_period': 'Friday Night', 'temperature': 72, 'forecast': 'Chance Showers And Thunderstorms', 'temp_icon': 'https://api.weather.gov/icons/land/night/tsra_hi,40/tsra_hi,20?size=medium'} }
Django模板遍历实现
在模板中直接遍历字典的键值对,即可获取每个时段的完整信息:
{% for key, value in weather_dict.items %} <div class="col-lg-3 col-sm-4"> <div class="card h-100 border border-dark rounded"> <img class="card-image" src={{value.temp_icon}}> </img> <div class="card-body"> <h2>{{ value.time_period }}, {{ value.temperature }} F</h2> <p class="card-text">{{ value.forecast }}</p> </div> </div> </div> {% endfor %}
内容的提问来源于stack exchange,提问作者Thomas Toquothty
相关产品推荐
相关产品推荐

