[英]Using SQLAlchemy, can I join a Python object (i.e. a list) within a Query?
Assuming I have a Postgres-DB table looking like this (with with many more rows):假设我有一个看起来像这样的 Postgres-DB 表(有更多行):
|------|-------|
|col1 |col 2 |
|------|-------|
|a1 |10 |
|a2 |55 |
|a3 |24 |
|------|-------|
And a List in Python with Tuples looking like this: Python 中的列表如下所示:
|------|-------|
|a1 |1 |
|a3 |2 |
|------|-------|
During runtime I now want to (inner) join the table with the list without having to persist the list as a DB object.在运行时,我现在想(内部)将表与列表连接起来,而不必将列表作为 DB object 保存。
What does work, is to filter using the list and SQLAlchemys .in_
operator.起作用的是使用列表和 SQLAlchemys
.in_
运算符进行过滤。
However when I try db.query(Table).join(list)
I get this error:但是,当我尝试
db.query(Table).join(list)
时,出现此错误:
sqlalchemy.exc.NoInspectionAvailable: No inspection system is available for object of type
sqlalchemy.exc.NoInspectionAvailable:没有适用于 object 类型的检测系统
Of course a workaround would be to first fetch all elements from the db using the filter operator and then using python for the join...but it feels like there should be a当然,一种解决方法是首先使用过滤器运算符从数据库中获取所有元素,然后使用 python 进行连接......但感觉应该有一个
If I understood correctly and you want to only get the rows where col1 == tuple[0]
, you can use the sqlalchemy filter
and in_
operators:如果我理解正确并且您只想获取
col1 == tuple[0]
的行,则可以使用 sqlalchemy filter
和in_
运算符:
tuples_list = [('a1', 1), ('a3', 2)]
search_dict = dict(tuples_list) # Convert to dict
res = db.query(Table).filter(Table.col1.in_(search_dict.keys())).all()
for instance in res:
instance.col2 = instance.col2 + search_dict[instance.col1]
There's also a detailed example without using the ORM here: SQLAlchemy IN clause这里还有一个不使用 ORM 的详细示例: SQLAlchemy IN 子句
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.