Keep the order of list in sql pagination

匿名 (未验证) 提交于 2019-12-03 02:51:02

问题:

I have a list with an order of insertion. I want to paginate the results using the same order. As you can see currently the output will be a different order.

following_companies_list_data = Company.query.filter(Company.id.in_(['2', '24', '1', '7', '373'])).paginate(             page, per_page=10, error_out=False)  companies = following_companies_list_data.items  for i in companies:     print i.id  7 24 373 2 1 

related question

回答1:

Solution based on this answer from related question

company_ids = ['2', '24', '1', '7', '373'] order_expressions = [(Company.id==i).desc() for i in company_ids] query = Company.query.filter(Company.id.in_(company_ids)).order_by(*order_expressions) following_companies_list_data = query.paginate(page, per_page=10, error_out=False) 

Also you can use idx function from intarray module

from sqlalchemy import func company_ids = ['2', '24', '1', '7', '373'] query = Company.query.filter(Company.id.in_(company_ids)).order_by(func.idx(company_ids, Company.id)) following_companies_list_data = query.paginate(page, per_page=10, error_out=False) 


回答2:

I think the easiest way to do this is to paginate your list of IDs before even querying:

company_ids_page = company_ids[page * 10:(page + 1) * 10] q = Company.query.filter(Company.id.in_(company_ids_page)) 

Then, reorder companies based on the order of your ids:

companies_map = {c.id: c for c in q} companies = [companies_map[i] for i in company_ids_page] 

If you need the fancy features of Pagination objects you can probably create a similar class for lists.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!