[Solved]-How to sort a list of objects in a template in alphabetic order?


You’ll need to write a custom filter which sorts by lower case. It’s pretty simple:

def sort_lower(lst, key_name):
    return sorted(lst, key=lambda item: getattr(item, key_name).lower())

But if your list is a set of objects from the database, you shouldn’t really be sorting them in Python – you should get the database to return them in the order you want.


How are you using the filter? It should be exactly the same as the dictsort one: object_list|sort_lower:"name".

To sort the queryset in the database, you can use the extra method to add a lower-case version of the field:

MyModel.objects.all().extra(select={'lower_name': 'LOWER(NAME)'}, order_by='lower_name')


A very old question, but the issue just came up for me. Just add .lower to dictsort, e.g.:

{% for item in object_list|dictsort:"name.lower" %}



I know this is an old question, but the easiest way I see to sort a list case insensitive is:


See link for reference:

You can test it using this code:

my_list = ["alice", "Bob", "eve", "Zoe"]
print("case sensitive list:")

print("case insensitive list:")

Then when you display your list in templates the items will already be sorted.



In fact, I looked at the original code of dictsort in .../lib/python2.7/site-packagesdjango/template/defaultfilters.py. And, I just added a customized cmp method:

def sort_lower(value, arg):
        return sorted(value, key=Variable(arg).resolve,
                      cmp=lambda x,y: cmp(x.lower(), y.lower()))
    except (TypeError, VariableDoesNotExist):
        return ''

This way allow to sort by subfields (e.g. field1.field2) which was needed in my case.


Leave a comment