python - Sqlalchemy get results in the same order -
i using query
users = user.query.filter(user.id.in_(user_ids)).all()
i want users
in same order in user_ids
. there anyway can directly in query or have sort again? if have sort again, pythonic way of sorting lists of objects based on list of ids.
this possible, though ugly, postgresql 9.4+ , sqlalchemy 0.9.7+. build map of id -> ordinal, use jsonb ->
operator find ordinal each user id (->
requires text
json keys
from sqlalchemy.sql.postgresql import jsonb, text sqlalchemy.sql import cast id_order = { str(v): k 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 create sql order similar to
order cast('{"1": 2, "3": 0, "2": 1}' jsonb) -> cast(user.id text)
for other databases sort in client - though means cannot browse through results.
the efficient code sort on client is:
id_order = { v: k k, v in enumerate(user_ids) } users = sorted(users, key=lambda u: id_order.get(u.id))
Comments
Post a Comment