IT박스

django 템플릿의 사전에서 사전을 반복하는 방법은 무엇입니까?

itboxs 2020. 7. 25. 10:43
반응형

django 템플릿의 사전에서 사전을 반복하는 방법은 무엇입니까?


내 사전은 다음과 같습니다 (사전 내의 사전).

{'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 %}

그러나 이것은 아무것도 표시하지 않습니다.

내가 뭘 잘못하고 있죠?


귀하의 데이터가-

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

data.items()메소드를 사용하여 사전 요소를 가져올 수 있습니다 . 장고 템플릿에서 우리는 넣지 않습니다 (). 언급 된 일부 사용자 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>

이 논리를 특정 전략으로 확장 할 수 있다고 확신합니다.


To iterate over dict keys in a sorted order - First we sort in python then iterate & render in django template.

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

In template file:

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

This answer didn't work for me, but I found the answer myself. No one, however, has posted my question. I'm too lazy to ask it and then answer it, so will just put it here.

This is for the following query:

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

In template:

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

참고URL : https://stackoverflow.com/questions/8018973/how-to-iterate-through-dictionary-in-a-dictionary-in-django-template

반응형