Django对象不可迭代

时间:2013-04-24 18:52:30

标签: django django-templates

我有一个对象,我正试图在我的模板中迭代。

我的问题是其中一个字段响应包含 json 数据,我收到此错误消息

交易'对象不可迭代

{% for item in transaction %}
    {{ item.notjson_fields}}

    {% for jsonItem in item.response %} 

       {{jsonItem}}

    {% endfor %}

{% endfor %}

型号:

 date_created = models.DateTimeField(auto_now_add=True)
 request = JSONField()
 response = JSONField()

2 个答案:

答案 0 :(得分:2)

您正在尝试迭代一个不可迭代的Transaction对象。

尝试类似

的内容
{{ transaction.notjson_fields}}

{% for jsonItem in transaction.response %} 
    {{ jsonItem }}
{% endfor %}

虽然不知道Transaction看起来像

,但我无法确定

编辑:

由于响应是JSONField,您可以像dict一样访问它。只是做

{{ transaction.response.amount }}

答案 1 :(得分:1)

如果像Ngenator所说,你的字段不是JSON对象而是字符串,你可能需要先加载它。首先注册一个新的模板标签

    from django import template
    register = template.Library()
    import json

    @register.filter
    def load_json(value):
        return json.loads(value)

然后获取(仅)模板中的金额

    {% with transaction.response|load_json as jsondict %}
    {% for k, v in jsondict.items %}
        {% if k == "amount" %}
            <td>{{ v }}</td>
        {% endif %}   
    {% endfor %}
    {% endwith %}

祝你好运。

相关问题