Python 通过Django模板中的列表字典进行处理
我有一本字典,看起来像这样:list={item:[东西,东西,东西],item:[东西,东西]} 我目前正在尝试显示所有项目和类似的内容:Python 通过Django模板中的列表字典进行处理,python,django,for-loop,django-templates,Python,Django,For Loop,Django Templates,我有一本字典,看起来像这样:list={item:[东西,东西,东西],item:[东西,东西]} 我目前正在尝试显示所有项目和类似的内容: Item thing thing thing Item thing thing 我试过了 {% for item, things in list %} -{{Item}} {% for thing in things %} {{thing}} {% endfor %}
Item
thing
thing
thing
Item
thing
thing
我试过了
{% for item, things in list %}
-{{Item}}
{% for thing in things %}
{{thing}}
{% endfor %}
{% endfor %}
但是我的输出看起来有点像
-
-
-
-
-
我以前试过
{% for item in list %}
-{{item}}
{% for thing in list[item] %}
{{thing}}
{% endfor %}
{% endfor %}
这根本不起作用。您应该使用
list.items
来指定要在(键、值)元组上迭代,而不是在键上迭代(就像在Python代码中一样)
此外,如果希望输出更具可读性,则必须包含一些换行符
像这样的方法应该会奏效:
{% for item_name, things in list.items %}
-{{item_name}}<br />
{% for thing in things %}
{{thing}}<br />
{% endfor %}
{% endfor %}
{%for item_name,things in list.items%}
-{{item_name}}
{%表示事物中的事物%}
{{thing}}
{%endfor%}
{%endfor%}
您应该使用list.items
来指定要在(键、值)元组上迭代,而不是在键上迭代(就像在Python代码中一样)
此外,如果希望输出更具可读性,则必须包含一些换行符
像这样的方法应该会奏效:
{% for item_name, things in list.items %}
-{{item_name}}<br />
{% for thing in things %}
{{thing}}<br />
{% endfor %}
{% endfor %}
{%for item_name,things in list.items%}
-{{item_name}}
{%表示事物中的事物%}
{{thing}}
{%endfor%}
{%endfor%}
正是我想要的,谢谢!一个问题。项目有一个字段,该字段是模型x的MTM。模型x具有属性名称。{{item.x.name}
没有显示的原因是什么?{{{item.x.name}
表示您访问项目
上的x
字段。如果字段x
对于一个模型来说是m2m,但它实际上是一个ManyRelatedManager
,并且不表示相关的模型实例(它在任何地方都没有意义,因为您可以有多个相关对象)。啊!那肯定是有道理的,我没想过。正是我想要的,谢谢!一个问题。项目有一个字段,该字段是模型x的MTM。模型x具有属性名称。{{item.x.name}
没有显示的原因是什么?{{{item.x.name}
表示您访问项目
上的x
字段。如果字段x
对于一个模型来说是m2m,但它实际上是一个ManyRelatedManager
,并且不表示相关的模型实例(它在任何地方都没有意义,因为您可以有多个相关对象)。啊!那肯定有道理,我没想过。