python - 如何在 HTML 中解析来自 Django 的 .serialize('json', data) 的输出
问题描述
我正在尝试遍历序列化的 JSON 对象并将其显示为列表,但不是列出我想要的属性,而是循环遍历 JSON 字符串中的每个单独的字符。当我对字典列表执行相同操作时,它可以工作。我究竟做错了什么?
普泰洪代码:
def menu(request):
# This is the object that I want to parse
dishes = Dish.objects.all()
dishes_ser = serializers.serialize('json', dishes)
# This list is copy-pasted directly from the output of the serialized query
to see if I could get that to work
check = [
{"model": "orders.dish", "pk": 1, "fields": {"dish": "Pizza"}},
{"model": "orders.dish", "pk": 3, "fields": {"dish": "Sub"}},
{"model": "orders.dish", "pk": 5, "fields": {"dish": "Pasta"}},
{"model": "orders.dish", "pk": 6, "fields": {"dish": "Salad"}},
{"model": "orders.dish", "pk": 7, "fields": {"dish": "Dinner platter"}}
]
context = {
'dishes': dishes_ser,
'check': check,
}
return render(request, "menu.html",context)
HTML
{% extends "layout.html" %}
{% block title %}
Menu
{% endblock %}
{% block content %}
<h1>Menu</h1>
<a href="/">Home</a>
Raw output of the check variable as received from Django:
<br />
<br />
{{check}}
<br/>
<br/>
<ul>
{% for data in check %}
<li>{{ data.fields.dish }}</li>
{% empty %}
<li>No Dishes</li>
{% endfor %}
</ul>
<br/>
Raw output of the dishes variable as received from Django::
<br />
<br />
{{dishes}}
<br/>
<br/>
<ul>
{% for data in dishes %}
<li>{{ data.fields.dish }}</li>
{% empty %}
<li>No Dishes</li>
{% endfor %}
</ul>
{%endblock%}
结果
HTML 页面的屏幕截图
解决方案
这是因为当您使用 序列化时serializer.serialize
,它会返回一个字符串。您需要将其转换为 json 对象,如下所示:
import json
json_data = json.loads(dishes_ser)
# then pass this as context
context = {
'dishes': json_data,
'check': check,
}
但是,当您可以直接将查询集发送到模板并像这样使用它时,为什么需要这样做:
// context
context = {
'dishes': Dish.objects.all(),
'check': check,
}
// template
{% for data in dishes %}
<li>{{ data.dish }}</li>
{% empty %}
<li>No Dishes</li>
{% endfor %}
推荐阅读
- java - 如何使用mybatis实现递归映射?
- sql-server - Sql Server左连接不返回匹配的行
- sony-audio-control-api - 我的 HT-CT800 不支持某些 get API 函数
- codenameone - 我可以在 Windows 10 桌面计算机上执行由 Codename One 生成的 App Windows UWP 吗?
- html - 修复字体差异
- php - SQLSTATE [22P02]:无效的文本表示:7 错误:整数的无效输入语法:“”
- c# - 插入外键记录 asp.net mvc 控制器
- android - 动态更改 chromecast 接收器 ID
- javascript - 在 React Native 中使用 navigator.geolocation.getCurrentPosition 以哪个单位显示精度?
- java - 添加 CLASSPATH 后无法找到或加载主类