开发者

How do I sort a list of python Django objects?

开发者 https://www.devze.com 2022-12-31 23:23 出处:网络
In Django, I have a model object in a list. [object, object, object] Each object has \".name\" which is the 开发者_StackOverflow社区title of the thing.

In Django, I have a model object in a list.

[object, object, object]

Each object has ".name" which is the 开发者_StackOverflow社区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())


catlist.sort(key=lambda x: x.name.lower())


Without the call to lower(), the following could be considered slightly cleaner than using a lambda:

import operator
catlist.sort(key=operator.attrgetter('name'))

Add that call to lower(), and you enter into a world of function-composition pain. Using Ants Aasma's compose() found in an answer to this other SO question, you too can see the light that is functional programming (I'm kidding. All programming paradigms surely have their time and place.):

>>> def compose(inner_func, *outer_funcs):
...     if not outer_funcs:
...         return inner_func
...     outer_func = compose(*outer_funcs)
...     return lambda *args, **kwargs: outer_func(inner_func(*args, **kwargs))
...
>>> class A(object):
...   def __init__(self, name):
...     self.name = name
...
>>> L = [A(i) for i in ['aa','a','AA','A']]
>>> name_lowered = compose(operator.attrgetter('name'), 
                           operator.methodcaller('lower'))
>>> print [i.name for i in sorted(L, key=name_lowered)]
['a', 'A', 'aa', 'AA']
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号