How to sort alphanumeric list of Django model objects
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 开发者_StackOverflow社区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.attrgetter
to sort your objects by the value of an attribute:
import operator
class Foo:
def __init__(self, name):
self.name = name
l = [Foo('AA'), Foo('a'), Foo('AB')]
l.sort(key=operator.attrgetter('name'))
print [o.name for o in l]
['AA', 'AB', 'a']
Here is another answer I provided which defines a function to perform alpha-numeric sort in "human" order. Merging the _human_key
function into the example above, you could do:
l.sort(key=lambda x: _human_key(x.name))
print [o.name for o in l]
['a', 'AA', 'AB']
I had a similar issue where I tried to order a Queryset in a similar manner although I use a custom function to accomplish the order
1AreaDesk.
2-1-1Desk.
10AreaDesk.
AreaDesk.
Desk1
I realized that using the Lower function from Django produced the same result from django.db.models.functions import Lower
eg
Model.objects.filter(**filter_query).order_by(Lower("attribute_name")
Try this:
result = Take.objects.order_by('name')
for x in result:
print x
However, the example ordering you mention is not a normal alphanumeric (lexicographic) ordering as I know it. Instead, it would be:
10A
1A
2A
A1
A10
A11
A2
B2
B4
If you really want the ordering you specify, you'd have to get more creative.
精彩评论