首页 > 解决方案 > SQLAlchemy 从表中不存在的列表中查找 ID

问题描述

我有一个包含一些记录的表(每条记录都有一个 id - 主键)。现在我需要从指定的列表/集中选择表中不存在的所有 id。我正在使用 postgres 数据库和 sqlalchemy 作为 ORM。请建议必须执行此类查询。

标签: databasesqlalchemy

解决方案


对于非常大的集合可能效率不高,但演示的流程很简单:

my_list = [1, 2, 3, 4, 5]
missing_from_table = []
for id in my_list:
    result = session.query(Model.id).get(id)  # result is a tuple
    if not result:
        missing_from_table.append(id)

print(f'The following ids are not in the table: {missing_from_table}')

另一种选择是:

my_list = [1, 2, 3, 4, 5]
all_ids = [r.id for r in session.query(Model.id).all()]
missing_from_table = [id for id in my_list if id not in all_ids]

推荐阅读