I am trying to port the answer to the question posed in How to sort alpha numeric set in python to Django. I have a list of Django model instances returned by a query and I can’t work out how to use lambda to construct an elegant (or otherwise!) sort function.
If my model contains a ‘name’ attribute – e.g.
result = Take.objects.all()
for i in result:
print i.name
How can I sort the resulting list of objects by the name attribute and apply a number of tests?
i.e. my name value could be ‘1A’,’1′,’A1′,’001A’ etc
e.g.
to give this ordering (based on name)
1A
2A
10A
A1
A2
A10
A11
B2
B4
Use
operator.attrgetterto sort your objects by the value of an attribute:Here is another answer I provided which defines a function to perform alpha-numeric sort in “human” order. Merging the
_human_keyfunction into the example above, you could do: