我在itertools.groupby
对查询集的元素进行分组时遇到了一个奇怪的问题。我有一个模型Resource
:
from django.db import models
TYPE_CHOICES = (
('event', 'Event Room'),
('meet', 'Meeting Room'),
# etc
)
class Resource(models.Model):
name = models.CharField(max_length=30)
type = models.CharField(max_length=5, choices=TYPE_CHOICES)
# other stuff
我的 sqlite 数据库中有几个资源:
>>> from myapp.models import Resource
>>> r = Resource.objects.all()
>>> len(r)
3
>>> r[0].type
u'event'
>>> r[1].type
u'meet'
>>> r[2].type
u'meet'
所以如果我按类型分组,我自然会得到两个元组:
>>> from itertools import groupby
>>> g = groupby(r, lambda resource: resource.type)
>>> for type, resources in g:
... print type
... for resource in resources:
... print '\t%s' % resource
event
resourcex
meet
resourcey
resourcez
现在我的观点也有同样的逻辑:
class DayView(DayArchiveView):
def get_context_data(self, *args, **kwargs):
context = super(DayView, self).get_context_data(*args, **kwargs)
types = dict(TYPE_CHOICES)
context['resource_list'] = groupby(Resource.objects.all(), lambda r: types[r.type])
return context
但是当我在我的模板中迭代它时,缺少一些资源:
<select multiple="multiple" name="resources">
{% for type, resources in resource_list %}
<option disabled="disabled">{{ type }}</option>
{% for resource in resources %}
<option value="{{ resource.id }}">{{ resource.name }}</option>
{% endfor %}
{% endfor %}
</select>
这呈现为:
我在想子迭代器已经被迭代了,但我不确定这是怎么发生的。
(使用 python 2.7.1,Django 1.3)。
(编辑:如果有人读到这个,我建议使用内置regroup
模板标签而不是使用groupby
.)