Django项目中如何将JSONField数据通过ListView展示为HTML表格?
Django中把JSONField数据转为HTML表格展示
前提假设
假设你的模型定义如下(已包含JSONField):
# models.py from django.db import models class YourModel(models.Model): json_data = models.JSONField() # 其他业务字段...
ListView视图常规配置:
# views.py from django.views.generic import ListView from .models import YourModel class YourModelListView(ListView): model = YourModel template_name = 'your_template.html' context_object_name = 'items'
方法一:模板中直接遍历生成表格
根据JSON数据的结构,分两种场景处理:
场景1:JSON是单条键值对(如{"name": "张三", "age": 25, "email": "zhangsan@xxx.com"})
在模板your_template.html中直接循环键值生成表格:
{% for item in items %} <h4>数据ID: {{ item.id }}</h4> <table border="1" cellpadding="8" cellspacing="0"> <thead> <tr> {% for key in item.json_data.keys %} <th>{{ key }}</th> {% endfor %} </tr> </thead> <tbody> <tr> {% for value in item.json_data.values %} <td>{{ value }}</td> {% endfor %} </tr> </tbody> </table> <br> {% endfor %}
场景2:JSON是多条数据组成的数组(如[{"name": "张三", "age":25}, {"name":"李四", "age":30}])
调整模板逻辑,先取第一条数据的键作为表头,再循环每条数据生成行:
{% for item in items %} <h4>数据ID: {{ item.id }}</h4> {% if item.json_data %} <table border="1" cellpadding="8" cellspacing="0"> <thead> <tr> {% for key in item.json_data.0.keys %} <th>{{ key }}</th> {% endfor %} </tr> </thead> <tbody> {% for entry in item.json_data %} <tr> {% for value in entry.values %} <td>{{ value }}</td> {% endfor %} </tr> {% endfor %} </tbody> </table> {% else %} <p>无JSON数据</p> {% endif %} <br> {% endfor %}
方法二:模型中预处理数据,模板直接调用
如果JSON结构复杂,或需要复用表格逻辑,可在模型中添加方法统一处理数据格式:
# models.py class YourModel(models.Model): json_data = models.JSONField() def get_table_structure(self): """将JSON数据转为表格所需的表头+行数据结构""" table_data = [] # 处理单条键值对 if isinstance(self.json_data, dict): table_data.append({ 'headers': list(self.json_data.keys()), 'rows': [list(self.json_data.values())] }) # 处理多条数据的数组 elif isinstance(self.json_data, list) and self.json_data: headers = list(self.json_data[0].keys()) rows = [list(entry.values()) for entry in self.json_data] table_data.append({'headers': headers, 'rows': rows}) return table_data
模板中直接调用该方法渲染表格:
{% for item in items %} <h4>数据ID: {{ item.id }}</h4> {% for table in item.get_table_structure %} <table border="1" cellpadding="8" cellspacing="0"> <thead> <tr> {% for header in table.headers %} <th>{{ header }}</th> {% endfor %} </tr> </thead> <tbody> {% for row in table.rows %} <tr> {% for cell in row %} <td>{{ cell }}</td> {% endfor %} </tr> {% endfor %} </tbody> </table> {% empty %} <p>无JSON数据</p> {% endfor %} <br> {% endfor %}
内容的提问来源于stack exchange,提问作者morcilloso
相关产品推荐
相关产品推荐

