How to order data in sqlalchemy by list

前端 未结 4 722
佛祖请我去吃肉
佛祖请我去吃肉 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条回答
  • 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.

    0 讨论(0)
  • 2021-01-13 13:43

    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)
    
    0 讨论(0)
  • 2021-01-13 13:56

    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))
    
    0 讨论(0)
  • 2021-01-13 13:56

    You can try:

    results = session.query(user).limit(20).offset(10).order_by(*A)
    
    0 讨论(0)
提交回复
热议问题