Login

improved sortby template tag

Author:
gmandx
Posted:
July 2, 2009
Language:
HTML/template
Version:
Not specified
Tags:
template tag dictsort
Score:
1 (after 1 ratings)

Variation on dictsort using attribute access. Nested attributes can be used, like, "obj.attr.attr_attr"

Example usage:

{% for entry in entries|sortby:'category.title' %}

Based on 1609

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
def sortby(sequence, attribute):
    """
    Variation on dictsort using attribute access
    Nested attributes can be used, like, "obj.attr.attr_attr"
    """
    def deep_attr(obj, attr_list):
        if len(attr_list) == 1:
            return getattr(obj, attr_list[0])
        return deep_attr(getattr(obj, attr_list[0]), attr_list[1:])

    lst = list(sequence)
    lst.sort(key=lambda obj: deep_attr(obj, attribute.split('.')))
    return lst

More like this

  1. Hyperlink list filter by lifefloatsby 7 years, 2 months ago
  2. Calendar template-tag by masida 7 years, 11 months ago
  3. cache_smart template tag by michiel_1981 7 years ago
  4. Django template tag to hash/map a value to a unique web color. by danielsokolowski 3 years, 3 months ago
  5. Django forms add placeholder from help text template tag by Ahmad.Dukhan 9 months, 3 weeks ago

Comments

showell (on July 6, 2009):

Very nice.

#

Please login first before commenting.