SQLAlchemy从Table对象(从元数据或Session或其他方式)获取Mapper对象 [英] SQLAlchemy get Mapper object from Table object (from Metadata or Session or otherwise)

查看:562
本文介绍了SQLAlchemy从Table对象(从元数据或Session或其他方式)获取Mapper对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我偶尔会遇到这样的情况:我有一个表对象(例如由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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆