Need classic mapper example for SqlAlchemy single table inheritance

主宰稳场 提交于 2019-12-02 05:26:20

Manually mapping class inheritance hierarchies is laborious and not something I'd recommend, but here goes. Start by defining your table. Since using single table inheritance, it must include all the required columns:

metadata = MetaData()

employee = Table(
    'employee',
    metadata,
    Column('id', Integer, primary_key=True),
    Column('name', String(50)),
    Column('type', String(20)),
    Column('manager_data', String(50)),
    Column('engineer_info', String(50))
)

The plain Python classes:

class Employee:

    def __init__(self, name):
        self.name = name

class Manager(Employee):

    def __init__(self, name, manager_data):
        super().__init__(name)
        self.manager_data = manager_data

class Engineer(Employee):

    def __init__(self, name, engineer_info):
        super().__init__(name)
        self.engineer_info = engineer_info

And the classical mappings:

mapper(Employee, employee,
       polymorphic_on=employee.c.type,
       polymorphic_identity='employee',
       exclude_properties={'engineer_info', 'manager_data'})


mapper(Manager,
       inherits=Employee,
       polymorphic_identity='manager',
       exclude_properties={'engineer_info'})


mapper(Engineer,
       inherits=Employee,
       polymorphic_identity='engineer',
       exclude_properties={'manager_data'})

Note how you have to limit the mapped properties manually in each mapper, which will become hard to maintain with larger hierarchies. When using Declarative all that is handled for you.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!