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

Comments

showell (on July 6, 2009):

Very nice.

#

(Forgotten your password?)

You may use Markdown syntax here, but raw HTML will be removed.