如何将JSON数据作为类QuerySet对象传入Django模板
Django 视图向模板传递结构化客户列表数据的实现方案
视图层代码编写
将你已存储的客户列表数据通过render的第三个参数(上下文字典)传入模板,不需要对原有结构做额外的JSON序列化处理:
# views.py from django.shortcuts import render def get_customer_list(request): # 你原有存储的客户数据直接复用即可 customer_list = [ { "id": 6, "first_name": "Star", "last_initial": "W", "phone": "+918893972142", "email": "star@gmail.com", "date_created": "2020-10-12T17:17:17.629123Z", "orders": [] }, { "id": 4, "first_name": "Sam", "last_initial": "0", "phone": "+918766897214", "email": "sam@gmail.com", "date_created": "2020-10-12T17:13:33.435065Z", "orders": [] }, { "id": 3, "first_name": "Gaara", "last_initial": "W", "phone": "+918668972789", "email": "gaara@gmail.com", "date_created": "2020-10-12T17:08:44.906809Z", "orders": [ { "order_id": "9", "customer_id": "3", "customer_name": "Gaara W", "product_id": "3", "product_name": "Jet", "date_created": "2020-10-12T17:18:18.823289Z", "status": "Delivered" } ] } ] # 传入上下文,键名就是模板中循环使用的变量名 return render(request, "customer/index.html", { "customers": customer_list })
模板层循环渲染
在对应模板文件中通过{% for %}标签遍历传入的上下文变量,嵌套的订单数据可以在客户循环内部二次遍历:
<!-- templates/customer/index.html --> <div class="customer-container"> {% for customer in customers %} <div class="customer-card"> <h3>{{ customer.first_name }} {{ customer.last_initial }}</h3> <p>联系电话:{{ customer.phone }}</p> <p>邮箱:{{ customer.email }}</p> <p>注册时间:{{ customer.date_created }}</p> <div class="order-section"> <h4>历史订单</h4> {% for order in customer.orders %} <div class="order-item"> 订单号 {{ order.order_id }}:购买商品 {{ order.product_name }},当前状态 {{ order.status }} </div> {% empty %} <p>该客户暂无历史订单</p> {% endfor %} </div> </div> {% empty %} <p>暂无客户数据</p> {% endfor %} </div>
关键注意事项
- 不要将数据通过
json.dumps()转成字符串后传入模板,否则模板无法通过点语法直接读取字典/对象的属性值,仅需传入Python原生的列表、字典结构即可 - 配合
{% empty %}标签可以覆盖列表为空、嵌套订单为空的场景,避免页面出现无内容的空白区块 - 对于
date_created这类时间字段,可直接在模板中通过date过滤器自定义显示格式,无需在视图层提前转换
内容的提问来源于stack exchange,提问作者Rahul
相关产品推荐
相关产品推荐

