Python+SQLAlchemy:从InstrumentedList获取映射类?

2 投票
1 回答
2717 浏览
提问于 2025-04-17 18:43

我想动态获取使用了 SQLAlchemy 的映射器类的 InstrumentedList 实例。

我有一个一对多的父类和子类关系(我们称这个列为 myRelation),而 parentInstance.myRelation 是 InstrumentedList 的实例。我可以通过获取 InstrumentedList 中第一个实例的类来解决这个问题,但如果 InstrumentedList 里没有对象,这个方法就不管用了。

原因是:我需要把一个包含映射器类 X 属性的 Python 字典添加到 InstrumentedList 中,但我在运行时不知道这个映射器类是什么。因为我不能直接添加一个字典,所以我需要先获取这个映射器类。

谢谢。

1 个回答

4

这个关系是通过 property 和被监控的列表关联起来的。所以我们先从这个简单的映射开始:

from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class A(Base):
    __tablename__ = "a"
    id = Column(Integer, primary_key=True)
    bs = relationship("B")

class B(Base):
    __tablename__ = "b"
    id = Column(Integer, primary_key=True)
    a_id = Column(Integer, ForeignKey('a.id'))

在任何最近版本的 SQLAlchemy 中,你可以这样查看:

print A.bs.property.mapper.class_

在 0.8 版本中,有更多的 API 可用,你可以这样做:

from sqlalchemy import inspect
print inspect(A.bs).mapper.class_

关于 inspect 的文档 -> http://docs.sqlalchemy.org/en/rel_0_8/core/inspection.html

关于 "mapper->class_" 的文档 -> http://docs.sqlalchemy.org/en/rel_0_8/orm/mapper_config.html#sqlalchemy.orm.mapper.Mapper.class_

撰写回答