I need to sort the catalog results by multiple fields.
In my case, first sort by year, then by month. The year and month field are included in my custom content type (item_publication_year and item_publication_month respectively).
However, I’m not getting the results that I want. The year and month are not ordered at all. They should appear in descending order i.e. 2006, 2005, 2004 etc.
Below is my code:
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
Anyone care to help?
A better bet is to use the
keyparameter for sorting:You can also use the
sorted()built-in function instead of usinglist(); it’ll return a sorted list for you, it’s the same amount of work for Python to first callliston the results, then sort, as it is to just callsorted:Naturally, both
item_publication_yearanditem_publication_monthneed to be present in the catalog metadata.