SQLAlchemy:仅访问Parent类时如何获取关联关系的具体类类型?
在SQLAlchemy中通过关联字段获取对应关联类
可以通过SQLAlchemy关联字段的内置属性来获取对应的关联类,以下是两种可行方法:
直接访问关联字段的
mapper属性
每个relationship对象都带有mapper属性,指向关联模型的映射器,通过mapper.class_就能拿到对应的类。结合你的场景,可在CustomBase中实现类方法来通用获取:class CustomBase(Base): @classmethod def get_related_class(cls, relationship_name): rel_field = getattr(cls, relationship_name) return rel_field.mapper.class_ # 调用示例 child_class = Parent.get_related_class("children") print(child_class is Child) # 输出 True使用
sqlalchemy.inspect工具
借助inspect可以获取模型的元数据信息,从中提取关联关系对应的类:from sqlalchemy.inspect import inspect class CustomBase(Base): @classmethod def get_related_class(cls, relationship_name): model_inspect = inspect(cls) rel = model_inspect.relationships[relationship_name] return rel.mapper.class_
注意:以上操作需要确保SQLAlchemy已经完成模型映射(即所有关联的模型类都已被加载并注册到元数据中),否则可能无法正确获取到关联类。
内容的提问来源于stack exchange,提问作者Mirodinho
相关产品推荐
相关产品推荐

