Custom comparison function with orderby in select()

49 views
Skip to first unread message

Ian W. Scott

unread,
Apr 30, 2015, 3:42:06 PM4/30/15
to web...@googlegroups.com
I want to sort the results of a select() based on a string field. Normally I can just use select(orderby=db.mytable.myfield), but the strings are not in Latin characters, so the default string sorting produces unacceptable results. 

I've figured out how to create a comparison function using the PyICU bindings to the ICU library. In a regular list sort this allows me to do something like this:

    from icu import Locale, Collator
    myloc = Locale('el')                                                
    col = Collator.createInstance(myloc)                     
    words = ['ἀγ', 'βλα', 'ὁμηρ']                                    
    sorted_words = sorted(words, cmp=col.compare) 

Is there any way to pass this kind of custom collating function to the select()?   

Anthony

unread,
Apr 30, 2015, 5:13:23 PM4/30/15
to web...@googlegroups.com
The sorting via orderby is handled by the database, so you can't use Python code for that, as it must be executed by the database. However, the Rows object has a .sort() method, which does the sorting in Python after the records are returned by the database. See http://web2py.com/books/default/chapter/29/06/the-database-abstraction-layer#find--exclude--sort.

Note, depending on the size of the dataset, sorting in Python might be slower than having the database handle it.

Anthony

Ian W. Scott

unread,
May 5, 2015, 4:35:03 PM5/5/15
to web...@googlegroups.com
A belated thanks, Anthony. I had forgotten about the rows.sort() method.
Reply all
Reply to author
Forward
0 new messages