Sqlalchemy filter by field in list but keep original order?

后端 未结 4 1366
时光说笑
时光说笑 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:36

    I also have the same problem using a MySQL database. This is what I did:

    my_list = [13,14,5,6,7]
    # convert my_list to str
    my_list_str = ','.join(map(str, my_list))
    

    And this is how my query looks like:

    checkpoints = (
        db_session.query(Checkpoint)
        .filter(Checkpoint.id.in_(my_list))
        .order_by('FIELD(id, ' + my_list_str + ')')
        .all()
    )
    

    FIELD() is a native function in MySQL.

    EDIT: So your query should look like this:

    my_list_of_ids_str = ','.join(map(str, my_list_of_ids)) 
    Shoe.query.filter(Shoe.id.in_(my_list_of_ids)).order_by('FIELD(id, ' + my_list_of_ids_str + ')').all()
    

    Cheers

提交回复
热议问题