SqlAlchemy 单表继承需要经典的映射器示例 [英] Need classic mapper example for SqlAlchemy single table inheritance

查看:18
本文介绍了SqlAlchemy 单表继承需要经典的映射器示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找到了一个如何使用类映射进行单表继承的示例.

I found an example of how to do single table inheritance using Class mappings.

http://docs.sqlalchemy.org/en/latest/orm/inheritance.html#single-table-inheritance

但在我的一生中,我找不到如何使用经典映射器执行此操作的示例,以便我可以将类和持久映射分开.

But for the life of me, I cannot find an example of how to do this with classic mapper so that I can keep my classes and persistent mappings separate.

如何将此示例转换为经典映射?我很清楚创建表,只是不确定如何实际构建映射器.

How do I convert this example into classic mapping? I am clear on creating the tables, just not sure how to actually structure the mapper.

在示例中,定义了以下类型:

In the example, there are the following types defined:

class Employee(Base):

class Manager(Employee):

class Engineer(Employee):

假设我已经创建了合适的表:

Assuming I have created the appropriate table:

employee = Table(...Column(type...))

我如何为映射器编写代码,以便经理和工程师生活在同一个表中(单表继承),按类型(经理"、工程师"或其他员工)区分?

How do I write code for the mapper so that both Manager and Engineer live in the same table (single table inheritance) discriminated by type ("manager", "engineer" or otherwise employee)?

谢谢.

推荐答案

手动映射类继承层次结构很费力,我不推荐这样做,但这里就是这样.首先定义您的表.由于使用单表继承,它必须包含所有必需的列:

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))
)

普通的 Python 类:

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

和经典映射:

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.

这篇关于SqlAlchemy 单表继承需要经典的映射器示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆