database - SQLAlchemy 从表中不存在的列表中查找 ID
问题描述
我有一个包含一些记录的表(每条记录都有一个 id - 主键)。现在我需要从指定的列表/集中选择表中不存在的所有 id。我正在使用 postgres 数据库和 sqlalchemy 作为 ORM。请建议必须执行此类查询。
解决方案
对于非常大的集合可能效率不高,但演示的流程很简单:
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]
推荐阅读
- flutter - 嵌套的 if 和 else 语句在 Flutter 或 dart 中如何工作?
- sql - 不能在黑斑羚中使用
- ios - 从闭包内部快速添加 VC 不起作用
- html - IOS 上的 HTML 表单验证
- typescript - jasmine 如何 spyOn 一个泛型方法
- c# - app.UseMiddleware 之间的 Net Core 区别
() 和 app.Use(context, next) - c# - async void 方法的异常处理
- javascript - 用开玩笑的结果简单测试一个 vue 组件失败
- c# - 是否可以在通过标签搜索的表单上有一个搜索框
- python - numpy as_strided 的反函数