내 사전은 다음과 같습니다 (사전 내의 사전).
{'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>
이 논리를 특정 전략으로 확장 할 수 있다고 확신합니다.
dict 키를 정렬 된 순서 로 반복하려면-먼저 파이썬으로 정렬 한 다음 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 %}
답변
data
템플릿에 컨텍스트로 변수 (사전 유형) 를 전달 하면 코드는 다음과 같아야합니다.
{% for key, value in data.items %}
<p>{{ key }} : {{ value }}</p>
{% endfor %}