Sort catalog results by multiple fields

I need to sort the results by several fields.

In my case, first sort by year, then by month. The year and month field is included in my own content type ( item_publication_year and item_publication_month respectively).

However, I do not get the results that I want. 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 

Can anybody help?

+4
source share
2 answers

It is best to use the key parameter to sort:

 results.sort(key=lambda b: (b.item_publication_year, b.item_publication_month)) 

You can also use sorted() inline function instead of using list() ; it will return the sorted list for you, this is the same amount of work for Python to first call list on the results and then sort, since just calling sorted :

 results = portal_catalog.searchResults(query) results = sorted(results, key=lambda b: (b.item_publication_year, b.item_publication_month)) 

Naturally, both item_publication_year and item_publication_month must be present in the catalog metadata.

+7
source

You can get several sortings directly from the search in the catalog using the advanced query , see also its official documents

+3
source

Source: https://habr.com/ru/post/1435064/


All Articles