首页 > 解决方案 > 如何在 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 页面的屏幕截图 HTML 页面的屏幕截图

标签: pythondjango

解决方案


这是因为当您使用 序列化时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 %}

推荐阅读