Get rows by id list keeping the order

23 views
Skip to first unread message

Carlos Cesar Caballero Díaz

unread,
Apr 22, 2018, 11:46:13 AM4/22/18
to web...@googlegroups.com
Hi guys, I have a list of ids, and I need to obtain the records keeping
the list order. In MySQL I can use FIELD() in the "order by" for that.
Can I get the ordered records using the DAL?

Greetings.

Anthony

unread,
Apr 22, 2018, 12:12:17 PM4/22/18
to web2py-users
The DAL doesn't have anything built in that will work across database backends, but if you are using MySQL, you should be able to do:

db(query).select(orderby='Field(id, %s)' % ', '.join(str(id) for id in list_of_ids))

Alternatively, if the list is not too long, you can just do the sorting in Python after selection:

db(query).select().sort(lambda r: list_of_ids.index(r.id))

Anthony

Carlos Cesar Caballero Díaz

unread,
Apr 22, 2018, 12:36:08 PM4/22/18
to web...@googlegroups.com

Thanks Anthony, I will go with the first option and guess how to adapt it to postgress too.

Greetings.


El 22/04/18 a las 12:12, Anthony escribió:
--
Resources:
- http://web2py.com
- http://web2py.com/book (Documentation)
- http://github.com/web2py/web2py (Source code)
- https://code.google.com/p/web2py/issues/list (Report Issues)
---
You received this message because you are subscribed to the Google Groups "web2py-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to web2py+un...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Leonel Câmara

unread,
Apr 23, 2018, 11:30:39 AM4/23/18
to web2py-users
I would make a function that automatically generated case statements for the orderby

def make_orderby(idlist):
    result
="CASE"
   
for i, el in enumerate(idlist):
        result
+= " WHEN id = %d THEN '%d' " % (el, i)
    result
+= " ELSE id END ASC"
   
return result  




I have not tested this...

Carlos Cesar Caballero Díaz

unread,
Apr 23, 2018, 11:50:45 AM4/23/18
to web...@googlegroups.com

Thanks Leonel, that sounds interesting, I will take a look.

Greetings.


El 23/04/18 a las 11:30, Leonel Câmara escribió:
Reply all
Reply to author
Forward
0 new messages