I have a list of IDs from an external postgresql database.
A = [1,2,3,4,5,6,7,98,0]
I would like to query the database using SQLAlchemy, but I would like to sort the data in postgresql by list.
I read a lot of documentation but cannot find any suggestions on how to do this.
So, in the finale, I would like to:
results = session.query(user).limit(20).offset(10).order_by(A)
Greetings
UPDATE:
I found a solution, it is not as good as I expected, but it works well. In any case, if you know the best solution, just let me know!
ids = ','.join([str(i) for i in A]) results = session.query(user).filter(user.id.in_(A)).\ limit(20).offset(10).\ order_by(" position(CONCAT(',',users.id::text,',') in ',{0},'.format(ids)")
source share