improved sortby template tag

 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. sortby template tag by showell 3 years, 10 months ago
  2. Recurse template tag for Django by Zarin 5 years, 3 months ago
  3. Class Feeds DRY TemplateTag by gmandx 3 years ago
  4. very archive template by stuntgoat 3 years, 7 months ago
  5. Sanitize HTML filter with tag/attribute whitelist and XSS protection by harrym 3 years, 10 months ago

Comments

showell (on July 6, 2009):

Very nice.

#

(Forgotten your password?)