Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy get Mapper object from Table object (from Metadata or Session or otherwise)

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)

In context, I have:

  • A sqlalchemy.schema.Table object;

  • A sqlalchemy.schema.MetaData object;

  • A sqlalchemy.orm.session.Session object representing the current session.

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?

like image 606
Coxy Avatar asked Jul 26 '18 01:07

Coxy


1 Answers

SQLAlchemy-utils has a function called get_mapper:

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]
like image 112
SuperShoot Avatar answered Oct 05 '22 10:10

SuperShoot