I have list of ID from external postgresql database.
A = [1,2,3,4,5,6,7,98,0]
I would to do query to database using SQLAlchemy, but I would
Another way would be to create another helper table which contains order positions for each user.id, join on it, and order:
A = [1,2,3,4,5,6,7,98,0]
stmt = " UNION ALL ".join( 'SELECT {0} AS user_id, {1} AS order_id'.format(uid, row)
for row, uid in enumerate(A))
ordq = text(stmt).columns(user_id=Integer, order_id=Integer).alias("t")
results = session.query(user).join(ordq, user.id == ordq.c.user_id).order_by(ordq.c.order_id).all()
I cannot judge whether this is better compared to your version, but it should at least be non-RDBMS specific.
Here's the example of sorting by using SQLAlchemy case expression.
from sqlalchemy import case
from core.orm import session
from core.orm import models
query = session.query(models.Model)
ids_list = [1, 2, 4, 3, 5]
# order query by index of id in `id_list`
id_ordering = case(
{_id: index for index, _id in enumerate(ids_list)},
value=models.Model.id
)
# order
query = query.order_by(id_ordering)
If you do not necessarily need to do this in SQL, you could simply sort the returned list of objects directly in python.
Example (using python's sorted function)
results = session.query(user).filter(user.id.in_(A)).all()
results = sorted(results, key=lambda o: A.index(o.id))
You can try:
results = session.query(user).limit(20).offset(10).order_by(*A)