0
在我看來,我創建列表下面字典從查詢集Django的模板循環collections.defaultdict:
#view.py
queryset = MyModel.objects.filter(owner=user, dashboard=tab).order_by('position')
my_dict = collections.defaultdict(lambda: collections.defaultdict(list))
for obj in queryset:
my_dict[int(obj.position.split('-')[0])][int(obj.position.split('-')[2])].append(obj)
return Response({'queryset': dict(my_dict)}, template_name='dashboard/_maps_tab.html')
位置字段是一個charFiled以下格式(拉姆達collections.defaultdict(名單))在創建my_dict
my_dict是
--[1] #group
----[1] #col 1
------ object1.1.1 #group.col.pk
------ object1.1.2
------ object1.1.3
----[2] #col 2
------ object1.2.4
----[3] #col3
------ object1.3.5
------ object1.3.6
--[2] #group
----[1] #col 1
------object2.1.7 #group.col.pk
--[3] #group
----[1] #col1
------ object3.1.8 #group.col.pk
----[2] #col2
------object3.2.9
------object3.2.10
在我的模板,我想這樣做
{% for groups in queryset.iteritems %}
groups = {{ groups }} <br>
{% for cols in groups %}
cols = {{ cols }} <br>
{% for objs in cols %}
{{ objs }} in <br><br>
{% for obj in objs %}
{{ obj.title }},
{{ obj.desc}},
{{ obj.fieldN }},
{% endfor %}
{% endfor %}
{% endfor %}
{% endfor %}
結果是
groups = (1, defaultdict(<type 'list'>, {1: [<Obj: Obj 1 by daviddd>, <Obj: Obj 2 by daviddd>, <Obj: Obj3 by daviddd>], 2: [<Obj: Obj 4 by daviddd>], 3: [<Obj: Obj 5 by daviddd>, <Obj: Obj 6 by daviddd>, <Obj: Obj 7 by daviddd>]}))
cols = 1
cols = defaultdict(<type 'list'>, {1: [<Obj: Obj 1 by daviddd>, <Obj: Obj 2 by daviddd>, <Obj: Obj3 by daviddd>], 2: [<Obj: Obj 4 by daviddd>], 3: [<Obj: Obj 5 by daviddd>, <Obj: Obj 6 by daviddd>, <Obj: Obj 7 by daviddd>]})
groups = (2, defaultdict(<type 'list'>, {1: [<Obj: Obj 7.7 by daviddd>]}))
cols = 2
cols = defaultdict(<type 'list'>, {1: [<Obj: Obj 7.7 by daviddd>]})
groups = (3, defaultdict(<type 'list'>, {1: [<Obj: Obj 7.8 by daviddd>]}))
cols = 3
cols = defaultdict(<type 'list'>, {1: [<Obj: Obj 7.8 by daviddd>]})
我試圖做{% for cols in groups.1 %}
,但它不工作(空)。 如果我這樣做{%for cols in groups.iteritems%}我有:「Int不可迭代」。
看着https://code.djangoproject.com/ticket/16335我的情況是
my_dict = collections.defaultdict(lambda: collections.defaultdict(list))
dictionary['foo']['foo1'].append('bar')
我該如何解決?
在此先感謝!
d
使用[Django的MPTT(HTTPS: //github.com/django-mptt/django-mptt/) –
我從來沒有用django-mptt來達到這個目的,很高興知道。我必須保留字典結構,因爲它會加載一個複雜的HTML/jQuery頁面 – Daviddd