How to order data in sqlalchemy by list

前端 未结 4 747
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-13 13:27

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

4条回答
  •  旧时难觅i
    2021-01-13 13:42

    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.

提交回复
热议问题