gpt4 book ai didi

python - Django 重组列表

转载 作者:太空宇宙 更新时间:2023-11-03 19:08:13 25 4
gpt4 key购买 nike

我对regroup有一个问题在 Django .情况是:我有一个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>

获取框过滤器:

#!/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:
...

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

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

谢谢

最佳答案

为什么不直接按部分重新分组?

{% 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>

关于python - Django 重组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13938384/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com