如何在Django视图中使用zip实现数据的表格化展示?
问题描述
我有一个Django应用,尝试在模板中展示后端返回的内容。定义了FilterText类,包含三个返回数值列表的方法,通过show_extracted_data_from_file方法整合返回值,相关代码如下:
class FilterText: def total_cost_fruit(self): return [3588.20, 5018.75, 3488.16, 444] def total_cost_fruit2(self): return [3588.20, 5018.75, 3488.99] def total_cost_fruit3(self): return [3588.20, 5018.75, 44.99] def show_extracted_data_from_file(self): regexes = [ self.total_cost_fruit(), self.total_cost_fruit2(), self.total_cost_fruit3, ] matches = [(regex) for regex in regexes] return zip(matches)
视图函数test调用该方法并传入模板:
def test(request): content_pdf = "" filter_text = FilterText() content_pdf = filter_text.show_extracted_data_from_file() context = {"content_pdf": content_pdf} return render(request, "main/test.html", context)
模板通过表格渲染数据:
<div class="wishlist"> <table> <tr> <th>Method 1</th> <th>Method 2</th> <th>Method 3</th> </tr> {% for value in content_pdf %} <tr> <td>{{value.0}}</td> <td>{{value.1}}</td> <td>{{value.2}}</td> </tr> {% endfor %} </table> </div>
目前渲染结果是每行显示一个完整列表:
Method 1 Method 2 Method 3 [3588.2, 5018.75, 3488.16, 444] [3588.2, 5018.75, 3488.99] [3588.2, 5018.75, 44.99]
期望实现每行对应三个列表的元素,短列表元素耗尽后对应列留空:
Method 1 Method 2 Method 3 3588.2 3588.2 3588.2 5018.75 5018.75 5018.75 3488.16 3488.99 44.99 444
解决方案
1. 修复后端代码问题
现有代码存在两个关键问题:
regexes列表中self.total_cost_fruit3未加括号调用,传入的是方法对象而非列表数据zip(matches)仅将每个列表作为单独元素打包,无法实现按索引对齐多行数据
修改后的FilterText类(需导入itertools.zip_longest处理长度不一致的列表):
from itertools import zip_longest class FilterText: def total_cost_fruit(self): return [3588.20, 5018.75, 3488.16, 444] def total_cost_fruit2(self): return [3588.20, 5018.75, 3488.99] def total_cost_fruit3(self): return [3588.20, 5018.75, 44.99] def show_extracted_data_from_file(self): # 修复:调用total_cost_fruit3方法获取列表 regexes = [ self.total_cost_fruit(), self.total_cost_fruit2(), self.total_cost_fruit3(), ] # 使用zip_longest按索引对齐,短列表空缺处用None填充 return zip_longest(*regexes, fillvalue=None)
2. 调整模板渲染逻辑
模板中需判断元素是否为None,为空则显示空白字符串:
<div class="wishlist"> <table> <tr> <th>Method 1</th> <th>Method 2</th> <th>Method 3</th> </tr> {% for val1, val2, val3 in content_pdf %} <tr> <td>{{ val1 if val1 is not None else '' }}</td> <td>{{ val2 if val2 is not None else '' }}</td> <td>{{ val3 if val3 is not None else '' }}</td> </tr> {% endfor %} </table> </div>
逻辑说明
zip_longest(*regexes)会将三个列表按索引逐一配对,生成每行包含三个对应位置元素的元组;当短列表无对应索引元素时,用fillvalue指定的None填充- 模板的条件判断确保
None值显示为空,实现短列表耗尽后对应列留空的效果
内容的提问来源于stack exchange,提问作者mightycode Newton
相关产品推荐
相关产品推荐

