Django重新组合列表

时间:2012-12-18 17:31:05

标签: python django

我在Django中遇到regroup的问题。 情况是:我有一个来自views.py的字典,我需要做以下事情:

Box A_name:
1 section:
1.1 element 1
...
1.n element n

N section:
N.1 element
...
N.m element

Box B_name:
...

html中的代码是:

{% load get_boxfilter %}
{% regroup all_boxes|dictsort:"box_type" by box_type as type %}

<ul>
{% for pos in type %}
    <li> Box {{ pos.grouper|get_boxfilter }}
    <ul>
        {% for item in pos.list %}

          <li> element {{ item.name }} section {{ item.section }}</li>
        {% endfor %}
    </ul>
    </li>
{% endfor %}
</ul>

get_boxfilter:

#!/usr/bin/python
# -*- coding: utf-8 -*- 
from django import template
register = template.Library()


@register.filter(name='get_groupfilter')
def get_boxfilter(value):
    gb_list = [u"NULL", u"A_name", u"B_name", u"N_name" ]
    return gb_list[int(value)]

以盒子名称重新组合:

Box A_name:
1. element 1 section 1
2. element 2 section 2
3. element 3 section 1
Box B_name:
...

但如何按“section”分组(int值)?

Box A_name:
1 section:
1.1 element 1
1.2 element 3
2 section:
2.1 element 2

由于

1 个答案:

答案 0 :(得分:1)

为什么不按部分重新组合?

{% load get_boxfilter %}
{% regroup all_boxes by section as type %}

<ul>
{% for pos in type %}
    <li> Box {{ pos.type|get_boxfilter }}
    <ol style="list-style-type: decimal">
         <li>{{ pos.grouper }}</li>
         <ol style="list-style-type: decimal">
             {% for item in pos.list %}
                 <li> element {{ item.name }}</li>
             {% endfor %}
         </ol>
    </ol>
    </li>
{% endfor %}
</ul>