我需要按多个字段对目录结果进行排序.
就我而言,首先按年份排序,然后按月计算.年份和月份场均包含在我的自定义内容类型(item_publication_year以及item_publication_month分别).
但是,我没有得到我想要的结果.年份和月份根本没有订购.它们应按降序排列,即2006年,2005年,2004年等.
以下是我的代码:
def queryItemRepository(self):
"""
Perform a search returning items matching the criteria
"""
query = {}
portal_catalog = getToolByName(self, 'portal_catalog')
folder_path = '/'.join( self.context.getPhysicalPath() )
query['portal_type'] = "MyContentType"
query['path'] = {'query' : folder_path, 'depth' : 2 }
results = portal_catalog.searchResults(query)
# convert the results to a python list so we can use the sort function
results = list(results)
results.sort(lambda x, y : cmp((y['item_publication_year'], y['item_publication_year']),
(x['item_publication_month'], x['item_publication_month'])
))
return results
Run Code Online (Sandbox Code Playgroud)
有人在乎帮忙吗?
更好的选择是使用key参数进行排序:
results.sort(key=lambda b: (b.item_publication_year, b.item_publication_month))
Run Code Online (Sandbox Code Playgroud)
您也可以使用sorted()内置功能代替使用list(); 它会为你返回一个排序列表,它与Python首先调用list结果的工作量相同,然后排序,因为它只是调用sorted:
results = portal_catalog.searchResults(query)
results = sorted(results, key=lambda b: (b.item_publication_year, b.item_publication_month))
Run Code Online (Sandbox Code Playgroud)
当然,既item_publication_year和item_publication_month需要存在在目录中的元数据.