SqlAlchemy单表继承 - 使用base mapper加载继承的模型

时间:2015-09-08 11:31:51

标签: python inheritance orm sqlalchemy

我使用SqlAlchemy经典映射来组织我的映射器和模型。我想创建一个模型类层次结构。我使用下一个代码:

import sys
from sqlalchemy import Table
from sqlalchemy.orm import mapper
from some_module import BaseClass, child_classes

table = Table('tab1', MetaData(schema='public'),
              Column('id', BigInteger, primary_key=True), 
              Column('discrim', String(64)))

base_mapper = mapper(BaseClass, table)

module = sys.modules[__name__]
for cls in child_classes:
    # Each cls object has a class-level attribute `name`
    submapper = mapper(cls, inherits=base_mapper, local_table=None,
                       polymorphic_on=table.c.discrim,
                       polymorphic_identity=cls.name)
    setattr(module, cls.name + '_mapper', submapper)

然后我想使用base_mapper从数据库加载模型。

query = db_session.query(base_mapper)
query = query.filter(base_mapper.mapped_table.c.discrim == 'foo')
print(query.all())

我希望获得一组Foo类对象,但实际上我得到了BaseClass个对象。我做错了什么?

1 个答案:

答案 0 :(得分:0)

最终,我找到了解决方案。重点是将polymorphic_on=子句从子类映射器移动到基类映射器。

# ...
base_mapper = mapper(BaseClass, table, 
                     polymorphic_on=table.c.discrim)
# ...
for cls in child_classes:
    submapper = mapper(cls, inherits=base_mapper, 
                       polymorphic_identity=cls.name)