Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting the catalog results by multiple fields

Tags:

python

plone

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?

like image 735
Frankline Avatar asked Dec 26 '22 17:12

Frankline


1 Answers

A better bet is to use the key parameter for sorting:

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

You can also use the sorted() built-in function instead of using list(); it'll return a sorted list for you, it's the same amount of work for Python to first call list on the results, then sort, as it is to just call 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 need to be present in the catalog metadata.

like image 146
Martijn Pieters Avatar answered Dec 29 '22 09:12

Martijn Pieters