简体   繁体   English

如何将 SQLAlchemy 结果行转换为嵌套的字典

[英]How to translate SQLAlchemy result rows into nested dicts

I am evaluating a potential setup for using SQLAlchemy in an async/await FastAPI app.我正在评估在 async/await FastAPI应用程序中使用 SQLAlchemy 的潜在设置。 I am currently composing models and queries using declarative_base classes, and then executing the queries with Databases (the syntax is much more readable and easy to write for model classes; working directly with SQLAlchemy core tables is not my favorite activity).我目前正在使用declarative_base类编写模型和查询,然后使用数据库执行查询(模型类的语法更易读且易于编写;直接使用 SQLAlchemy 核心表不是我最喜欢的活动)。 This all works great.这一切都很好。

At this point, I have SQLAlchemy result rows, but I need to convert them into generic dicts, potentially nested due to eagerly loaded relationships (only type I will support in this environment).在这一点上,我有 SQLAlchemy 结果行,但我需要将它们转换为通用字典,由于急切加载的关系而可能嵌套(在这种环境中我将只支持类型)。 I can't use SQLAlchemy's ORM because 1) I don't have an engine or session ;我不能使用 SQLAlchemy 的 ORM,因为 1) 我没有enginesession and 2) the ORM assumes that it can just hit the database whenever it needs to load in objects, which is not the case in an async/await FastAPI app.和 2) ORM 假设它可以在需要加载对象时访问数据库,而在 async/await FastAPI 应用程序中则不是这种情况。

Does anyone have ideas or pointers for how to accomplish this?有没有人有关于如何实现这一点的想法或指示? I'm struggling to figure out how to associate result rows with particular relationship keys, in particular.我正在努力弄清楚如何将结果行与特定的关系键相关联,特别是。 I've been poking around in the SQLAlchemy internals for ideas, but it's pretty opaque since a lot of it assumes an entire layer of object caching and session/engine management that just isn't present in my setup.我一直在 Sqlalchemy 内部寻找想法,但它非常不透明,因为其中很多都假设整个层的对象缓存和会话/引擎管理在我的设置中不存在。

The two things I could use ideas about:我可以使用想法的两件事:

  1. How to map columns names like table_1_column_name to specific models and their properties如何将列名称(如table_1_column_name到特定模型及其属性
  2. How to detect and map relationships (potentially more than one level deep)如何检测和映射关系(可能深度不止一层)

Thanks for any help you can provide!感谢您的任何帮助,您可以提供!

Update: You can find a runnable example here: https://gist.github.com/onecrayon/dd4803a5099061fa48d52f2d4bc2396b (see lines 92-109 for the relevant place where I need to figure out how to convert a RowProxy to a nested dict by mapping the query column names to the names on the SQLAlchemy model).更新:您可以在这里找到一个可运行的示例: https ://gist.github.com/onecrayon/dd4803a5099061fa48d52f2d4bc2396b(有关我需要弄清楚如何通过映射将 RowProxy 转换为嵌套字典的相关位置,请参阅第 92-109 行查询列名称到 SQLAlchemy 模型上的名称)。

If you are db first, sqlalchemy execute method usually returns a Result Proxy object and you can get the result of it with its methods such as fetchone, first, fetchall and then cast it to list or dict.如果你是 db first,sqlalchemy execute 方法通常会返回一个Result Proxy对象,你可以通过它的方法获取它的结果,例如 fetchone、first、fetchall,然后将其转换为 list 或 dict。 You can see also this dock你也可以看到这个码头

Casting the object into a dict should work if the result is a raw SQLAlchemy row and not an ORM-mapped instance.如果结果是原始 SQLAlchemy 行而不是 ORM 映射实例, 则将对象转换为 dict应该可以工作。

Seeing from your comment on another answer, it looks like you need to map the result back into an ORM instance.从您对另一个答案的评论来看,您似乎需要将结果映射回 ORM 实例。 You can define declarative mappings so that your result gets translated back into a python instance.您可以定义声明性映射,以便将结果转换回 Python 实例。

SQLALchemy object has an option to return as dict - Here is the SQLALchemy source doc to help you. SQLALchemy 对象有一个选项可以作为 dict 返回——这里是 SQLALchemy 源文档来帮助你。 https://docs.sqlalchemy.org/en/13/orm/query.html#sqlalchemy.util.KeyedTuple._asdict https://docs.sqlalchemy.org/en/13/orm/query.html#sqlalchemy.util.KeyedTuple._asdict

Or You can go with the https://pythonhosted.org/dictalchemy which works as wrapper on top of SQLALchemy.或者你可以使用https://pythonhosted.org/dictalchemy ,它作为 SQLALchemy 之上的包装器。

Hope that helps.希望有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM