Login

improved sortby template tag

Author:
gmandx
Posted:
July 2, 2009
Language:
HTML/template
Version:
Not specified
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. Bootstrap Accordian by Netplay4 7 years, 9 months ago
  2. Bootstrap theme for django-endless-pagination? by se210 10 years, 9 months ago
  3. Bootstrap theme for django-endless-pagination? by se210 10 years, 9 months ago
  4. Reusable form template with generic view by roldandvg 10 years, 10 months ago
  5. Pagination Django with Boostrap by guilegarcia 10 years, 11 months ago

Comments

showell (on July 6, 2009):

Very nice.

#

Please login first before commenting.