Sqlalchemy filter by field in list but keep original order?

后端 未结 4 1365
时光说笑
时光说笑 2021-02-12 22:35

I have a Shoe model like this:

class Shoe(db.Model):
id = db.Column(db.Integer, primary_key = True)
asin = db.Column(db.String(20), index = True)
4条回答
  •  梦如初夏
    2021-02-12 22:57

    One way I've solved this problem in the past is by using a SQL CASE expression to tell the database in what order I'd like the rows returned. Using your example:

    from sqlalchemy.sql.expression import case
    
    ordering = case(
        {id: index for index, id in enumerate(my_list_of_ids)},
        value=Shoe.id
     )
    Shoe.query.filter(Shoe.id.in_(my_list_of_ids)).order_by(ordering).all()
    

提交回复
热议问题