将 sqlalchemy ORM 查询对象转换为 Pandas DataFrame 的 sql 查询

AZh*_*hao 6 sqlalchemy pandas

这个问题感觉非常简单,但我一直无法找到答案。

我有一个 ORM 查询对象,比如说

query_obj = session.query(Class1).join(Class2).filter(Class2.attr == 'state')
Run Code Online (Sandbox Code Playgroud)

我可以像这样将其读入数据帧:

testdf = pd.read_sql(query_obj.statement, query_obj.session.bind)
Run Code Online (Sandbox Code Playgroud)

但我真正想做的是使用传统的 SQL 查询而不是 ORM:

with engine.connect() as connection:
    # Execute the query against the database
    results = connection.execute(query_obj)
    # Fetch all the results of the query
    fetchall = results.fetchall()
    # Build a DataFrame with the results
    dataframe = pd.DataFrame(fetchall)
Run Code Online (Sandbox Code Playgroud)

其中 query 是传统的 SQL 字符串。现在,当我运行它时,我收到了“query_obj 不可执行”这样的错误。有人知道如何将 ORM 查询转换为传统查询吗?另外,在获取数据框后如何获取列?

为什么我这样做的上下文:我在我的数据库之上设置了一个 ORM 层,并使用它来将数据查询到Pandas DataFrame. 它有效,但它经常使我的记忆力最大化。我想通过一些字符串折叠来减少我的内存开销(此处概述的第 3 步:http : //www.mobify.com/blog/sqlalchemy-memory-magic/)。这需要(如果我在这里错了,请纠正我)不使用 read_sql 字符串,而是将查询的返回处理为原始元组。

jor*_*ris 4

长版本在 sqlalchemy 的常见问题解答中有详细描述:http://sqlalchemy.readthedocs.org/en/latest/faq/sqlexpressions.html#how-do-i-render-sql-expressions-as-strings-possible -内联绑定参数

简短的版本是:

statement = query.statement
print(statement.compile(engine))
Run Code Online (Sandbox Code Playgroud)

其结果可用于read_sql.