In Django, I have a model object in a list.
[object, object, object]
Each object has ".name" which is the title of the thing.
How do I sort alphabetically by this title?
This doesn't work:
catlist.sort(key=lambda x.name: x.name.lower())
Python lists have a built-in list. sort() method that modifies the list in-place. There is also a sorted() built-in function that builds a new sorted list from an iterable.
Method 2: Using sorted() method The sorted() function returns a sorted list of the iterable object given. You can choose between ascending and descending order. Numbers are sorted numerically, while strings are arranged alphabetically.
A simple solution is to use the list. sort() function to sort a collection of objects (using some attribute) in Python. This function sorts the list in-place and produces a stable sort. It accepts two optional keyword-only arguments: key and reverse.
catlist.sort(key=lambda x: x.name.lower())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With