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'
したがって、タイプ別にグループ化すると、自然に 2 つのタプルが得られます。
>>> 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
を使用することをお勧めします。)