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. Sanitize HTML filter with tag/attribute whitelist and XSS protection by harrym 2 years, 9 months ago
  2. Template Filter attr by marinho 4 years ago
  3. BetterForm with fieldsets and row_attrs by carljm 3 years, 3 months ago
  4. Custom CSS class in Form with template tag filter by fernandogrd 7 months ago
  5. TableSelectMultiple Widget by insin 4 years, 5 months ago

Comments

showell (on July 6, 2009):

Very nice.

#

(Forgotten your password?)