python - Sqlalchemy 按列表中的字段过滤但保持原始顺序?

标签 python sqlalchemy flask-sqlalchemy

我有一个像这样的鞋子模型:

class Shoe(db.Model):
id = db.Column(db.Integer, primary_key = True)
asin = db.Column(db.String(20), index = True)

我有一个像 ids = [2,1,3] 这样的 id 列表,当我查询 Shoe 模型时,结果在“ids”列表中有 id,我想返回: [{id:2, asin:"111"},{id:1, asin:"113"},{id:3, asin:"42"}] 但问题是使用下面的查询语句不会保留原始顺序,结果将随机返回。如何保持筛选所依据的列表的顺序?

不正确的一个:Shoe.query.filter(Shoe.id.in_(my_list_of_ids)).all()

最佳答案

如果您有一个合理的小型 ID 列表,您可以对每个 ID 单独执行 SQL 查询:

[Shoe.query.filter_by(id=id).one() for id in my_list_of_ids]

对于大量的id,SQL查询会耗时较长。然后,您最好使用单个查询并在第二步中以正确的顺序放置值(借用自 how to select an object from a list of objects by its attribute in python ):

shoes = Shoe.query.filter(Shoe.id.in_(my_list_of_ids)).all()
[next(s for s in shoes if s.id == id) for id in my_list_of_ids]

这是假设 id 是唯一的(在您的情况下它们应该是唯一的)。如果有多个具有相同 id 的元素,第一个方法将引发异常。

关于python - Sqlalchemy 按列表中的字段过滤但保持原始顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29326297/

相关文章:

python - SQLAlchemy - 与额外列的自引用多对多关系

python - 如何使用 flask 和 sqlalchemy 进行选择查询?

python - 打印不带 '/n' 分隔符的文本的输出

flask - 如何在 Flask 页面请求之间保留查询?

sql - 汇总 column_property 值

python - 将 Python 代码应用于 Sqlalchemy 过滤器

python - 从模型中获取 JSONAPI 模式

Python:当在append()函数中输入的对象发生变化时,对象列表也会发生变化

python - cv.GetSubRect 迁移到 OpenCV 4

python - Kivy:AttributeError: 'Label'对象没有属性 'a'