post_ids = [3, 4, 1]
q_subq = '\nUNION ALL\n'.join('SELECT {} AS key, {} AS sort_order'.format(
    _id, i) for i, _id in enumerate(post_ids))
s = select([literal_column('key', Integer), literal_column('sort_order',
    Integer)]).select_from(text('({}) AS helper'.format(text(q_subq)))).alias(
    'helper')
q = session.query(Post).join(s, Post.id == s.c.key).order_by(s.c.sort_order)
Ordering and pagination in SQL-alchemy using non-sql ranking