Django分区筛选器代码段

时间:2014-04-02 23:37:16

标签: python django code-snippets

我使用其中一个分区Django代码段将数据分成3列,一切正常,我不知道如何调用中间分区。

@register.filter
def partition(thelist, n):
try:
    n = int(n)
    thelist = list(thelist)
except (ValueError, TypeError):
    return [thelist]
p = len(thelist) / n
return [thelist[p*i:p*(i+1)] for i in range(n - 1)] + [thelist[p*(i+1):]]

模板

{% for x in y|partition:"3"|first %} (working, shows first 1/3)
{% for x in y|partition:"3"|middle %} (not working)
{% for x in y|partition:"3"|last %} (working, shows last 1/3)

显然"中间"是不正确的。我试过"第二"它也没有用。

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

firstlast是模板过滤器,用于获取列表的第一个和最后一个元素。没有模板过滤器来获取第二个,第三个等元素。您必须使用for item in ..构造:

{% for row in mylist|partition:"3" %}
    {% for item in row %}
        do something with {{ item }}
    {% endfor %}
{% endfor %}