我想将resultproxy对象转换为子查询以与ORM查询一起使用。这样做的程序是什么?我真的找不到任何例子。
答案 0 :(得分:3)
结果代理是将SELECT语句传递给数据库并执行时得到的 - 此时,不再有“查询”,因此从字面意义上讲,结果代理不是子查询。但是,您执行的SELECT语句可以改为 not ,并且很容易作为子查询传递到另一个查询中:
from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class A(Base):
__tablename__ = 'a'
id = Column(Integer, primary_key=True)
data = Column(String)
e = create_engine("sqlite://", echo=True)
Base.metadata.create_all(e)
sess = Session(e)
# test data.
sess.add_all([A(data="d%d" % i) for i in range(10)])
sess.commit()
# a query.
subq = sess.query(A.id).filter(A.data.in_(["d3", "d4", "d5"]))
# execute subquery, gives us a list of tuples
list_of_tuples = subq.all()
# execute subquery via Core, gives us a ResultProxy
result_proxy = sess.execute(subq)
# inject subq into another Query as a subquery()
q = sess.query(A).filter(A.data.in_(subq.subquery()))
a_from_subquery = q.all()