Django模板不能循环defaultdict

时间:2022-09-04 20:19:08
import collections

data = [
  {'firstname': 'John', 'lastname': 'Smith'}, 
  {'firstname': 'Samantha', 'lastname': 'Smith'}, 
  {'firstname': 'shawn', 'lastname': 'Spencer'}, 
]

new_data = collections.defaultdict(list)

for d in data:
    new_data[d['lastname']].append(d['firstname'])

print new_data

Here's the output:

输出:

defaultdict(<type 'list'>, {'Smith': ['John', 'Samantha'], 'Spencer': ['shawn']})

and here's the template:

这是模板:

{% for lastname, firstname in data.items %}
  <h1> {{ lastname }} </h1>
  <p> {{ firstname|join:", " }} </p>
{% endfor %}

But the loop in my template doesn't work. Nothing shows up. It doesn't even give me an error. How can i fix this? It's supposed to show the lastname along with the firstname, something like this:

但是我的模板中的循环不起作用。没有出现。它甚至没有给我一个错误。我该怎么解决这个问题呢?它应该显示姓和名,类似这样:

<h1> Smith </h1>
<p> John, Samantha </p>

<h1> Spencer </h1>
<p> shawn </p>

2 个解决方案

#1


36  

try:

试一试:

dict(new_data)

and in Python 2 it is better to use iteritems instead of items :)

在Python 2中,最好使用iteritems而不是item:

#2


71  

You can avoid the copy to a new dict by disabling the defaulting feature of defaultdict once you are done inserting new values:

在插入新值后,您可以禁用defaultdict功能的默认特性,以避免复制到新dict:

new_data.default_factory = None

Explanation

解释

The template variable resolution algorithm in Django will attempt to resolve new_data.items as new_data['items'] first, which resolves to an empty list when using defaultdict(list).

Django中的模板变量解析算法将尝试解析new_data。项目作为new_data['items']首先,在使用defaultdict(list)时解析为空列表。

To disable the defaulting to an empty list and have Django fail on new_data['items'] then continue the resolution attempts until calling new_data.items(), the default_factory attribute of defaultdict can be set to None.

若要禁用对空列表的默认值,并使Django在new_data['items']上失败,则继续解析尝试,直到调用new_data.items(), defaultdict词的default_factory属性可以设置为None。

#1


36  

try:

试一试:

dict(new_data)

and in Python 2 it is better to use iteritems instead of items :)

在Python 2中,最好使用iteritems而不是item:

#2


71  

You can avoid the copy to a new dict by disabling the defaulting feature of defaultdict once you are done inserting new values:

在插入新值后,您可以禁用defaultdict功能的默认特性,以避免复制到新dict:

new_data.default_factory = None

Explanation

解释

The template variable resolution algorithm in Django will attempt to resolve new_data.items as new_data['items'] first, which resolves to an empty list when using defaultdict(list).

Django中的模板变量解析算法将尝试解析new_data。项目作为new_data['items']首先,在使用defaultdict(list)时解析为空列表。

To disable the defaulting to an empty list and have Django fail on new_data['items'] then continue the resolution attempts until calling new_data.items(), the default_factory attribute of defaultdict can be set to None.

若要禁用对空列表的默认值,并使Django在new_data['items']上失败,则继续解析尝试,直到调用new_data.items(), defaultdict词的default_factory属性可以设置为None。