SQLAlchemy从Table对象(从元数据或Session或其他方式)获取Mapper对象 [英] SQLAlchemy get Mapper object from Table object (from Metadata or Session or otherwise)
问题描述
我偶尔会遇到这样的情况:我有一个表对象(例如由Metadata.tables
检索到),并且想要获取Mapper对象,该对象定义了从某些用户定义的类到Table的映射(然后最终映射的类)
I find myself occassionally in a situation where I have a table object (such as is retrieved by Metadata.tables
) and want to get the Mapper object which defines a mapping from some user-defined class to a Table (and then eventually the mapped Class)
在上下文中,我有:
-
一个
sqlalchemy.schema.Table
对象;
一个sqlalchemy.schema.MetaData
对象;
表示当前会话的sqlalchemy.orm.session.Session
对象.
我想要的是sqlalchemy.orm.mapper.Mapper
对象,该对象定义了用户定义的类与上面的Table
对象之间的映射.我找不到通过文档或通过检查这些对象及其可用方法来实现此目的的方法.有什么办法吗?
What I want is the sqlalchemy.orm.mapper.Mapper
object which defines a mapping between a user-defined class and the Table
object above. I can't find a way to get this via the docs or from inspecting these objects and their available methods. Is there any way to do this?
推荐答案
SQLAlchemy- utils 具有一个名为 get_mapper
的函数>:
SQLAlchemy-utils has a function called get_mapper
:
为给定的SQLAlchemy对象返回相关的SQLAlchemy映射器.
Return related SQLAlchemy Mapper for given SQLAlchemy object.
该函数将接受许多不同类型的对象,测试它是什么,然后执行返回映射器所需的逻辑.
That function will accept a number of different types of object, test what it is, and then perform the logic necessary to return the mapper.
If you are purely looking at getting the mapper from a table, this is a function inspired from their source code without any of the type checking/handling that they do in get_mapper
:
from sqlalchemy.orm import mapperlib
def find_table_mapper(tbl):
mappers = [
mapper for mapper in mapperlib._mapper_registry
if tbl in mapper.tables
]
if len(mappers) > 1:
raise ValueError(
"Multiple mappers found for table '%s'." % tbl.name
)
elif not mappers:
raise ValueError(
"Could not get mapper for table '%s'." % tbl.name
)
else:
return mappers[0]
这篇关于SQLAlchemy从Table对象(从元数据或Session或其他方式)获取Mapper对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!