This is very possible, though ugly, with PostgreSQL 9.4+ and SQLAlchemy 0.9.7+. Basically we build a map of id -> ordinal, then use the JSONB ->
operator to find the ordinal for each user id (->
requires TEXT
for JSON keys
from sqlalchemy.sql.postgresql import JSONB, TEXT
from sqlalchemy.sql import cast
id_order = { str(v): k for k, v in enumerate(user_ids) }
users = User.query.filter(User.id.in_(user_ids)).\
order_by(cast(id_order, JSONB)[cast(User.id, TEXT)])
This will create SQL ORDER BY similar to
ORDER BY CAST('{"1": 2, "3": 0, "2": 1}' AS JSONB) ->
CAST(user.id AS TEXT)
For other databases just sort it in the client - though it means you cannot browse through the results.
The efficient code to sort on client is:
id_order = { v: k for k, v in enumerate(user_ids) }
users = sorted(users, key=lambda u: id_order.get(u.id))