如何在Django模板中迭代字典中的字典?

2024-04-25 07:39:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我的字典看起来像这样(字典中的字典):

{'0': {
    'chosen_unit': <Unit: Kg>,
    'cost': Decimal('10.0000'),
    'unit__name_abbrev': u'G',
    'supplier__supplier': u"Steve's Meat Locker",
    'price': Decimal('5.00'),
    'supplier__address': u'No\r\naddress here',
    'chosen_unit_amount': u'2',
    'city__name': u'Joburg, Central',
    'supplier__phone_number': u'02299944444',
    'supplier__website': None,
    'supplier__price_list': u'',
    'supplier__email': u'ss.sss@ssssss.com',
    'unit__name': u'Gram',
    'name': u'Rump Bone',
}}

现在我只是想在我的模板上显示信息,但我正在努力。我的模板代码如下:

{% if landing_dict.ingredients %}
  <hr>
  {% for ingredient in landing_dict.ingredients %}
    {{ ingredient }}
  {% endfor %}
  <a href="/">Print {{ landing_dict.recipe_name }}</a>
{% else %}
  Please search for an ingredient below
{% endif %}

它只是在我的模板上显示“0”?

我也试过:

{% for ingredient in landing_dict.ingredients %}
  {{ ingredient.cost }}
{% endfor %}

这甚至没有显示结果。

我想也许我需要更深入地迭代一个层次,所以试着这样做:

{% if landing_dict.ingredients %}
  <hr>
  {% for ingredient in landing_dict.ingredients %}
    {% for field in ingredient %}
      {{ field }}
    {% endfor %}
  {% endfor %}
  <a href="/">Print {{ landing_dict.recipe_name }}</a>
{% else %}
  Please search for an ingredient below
{% endif %}

但这没有显示任何东西。

我做错什么了?


Tags: namein模板for字典unitdictdecimal
2条回答

假设你的数据是-

data = {'a': [ [1, 2] ], 'b': [ [3, 4] ],'c':[ [5,6]] }

可以使用data.items()方法获取字典元素。注意,在django模板中,我们不放置()。还有一些用户提到values[0]不起作用,如果是这样的话,请尝试values.items

<table>
    <tr>
        <td>a</td>
        <td>b</td>
        <td>c</td>
    </tr>

    {% for key, values in data.items %}
    <tr>
        <td>{{key}}</td>
        {% for v in values[0] %}
        <td>{{v}}</td>
        {% endfor %}
    </tr>
    {% endfor %}
</table>

我确信你可以把这个逻辑扩展到你的特定指令


要按排序顺序迭代dict键,请执行以下操作:首先使用python进行排序,然后使用django模板进行迭代和呈现。

return render_to_response('some_page.html', {'data': sorted(data.items())})

在模板文件中:

{% for key, value in data %}
    <tr>
        <td> Key: {{ key }} </td> 
        <td> Value: {{ value }} </td>
    </tr>
{% endfor %}

这个答案对我不起作用,但我自己找到了答案。不过,没有人把我的问题发出去。我太懒了 先问再答,所以就放在这里。

用于以下查询:

data = Leaderboard.objects.filter(id=custom_user.id).values(
    'value1',
    'value2',
    'value3')

在模板中:

{% for dictionary in data %}
  {% for key, value in dictionary.items %}
    <p>{{ key }} : {{ value }}</p>
  {% endfor %}
{% endfor %}

相关问题 更多 >

    热门问题