您的位置:首页 > 数据库

理解SQLAlchemy的表继承关系(2)-Single Table Inheritance

2015-12-09 11:36 1196 查看
Single Table Inheritance即单表继承,顾名思义,所有继承表的数据均保存在一个表。

该种继承比较容易理解。

class Employee(Base):
__tablename__ = 'employee'
id = Column(Integer, primary_key=True
name = Column(String(50))
manager_data = Column(String(50))
engineer_info = Column(String(50))
type = Column(String(20))
__mapper_args__ = {
'polymorphic_on':type,
'polymorphic_identity':'employee'
}
class Manager(Employee):
__mapper_args__ = {
'polymorphic_identity':'manager'
}
class Engineer(Employee):
__mapper_args__ = {
'polymorphic_identity':'engineer'
}


在上例中,Engineer和Manager均没有独立的表,所有数据均保存在基表Employee中,

同样的Employee使用polymorphic_on指定的字段来标识该行记录是属于哪个继承表的,而标识的字段串由继承表的

polymorphic_identity值指定。

在上例中polymorphic_on="type",Engineer的polymorphic_identity="engineer",

因此当你使用

Session.query(Engineer).all()

查询所有工程师时,相当于:

select * from employee where type="engineer"

小结:

1、所有继承表数据均在一个表中

2、基表的设计上应包含所有继承表的字段。

3、通过polymorphic_on来标识区分该记录属于哪个继承表.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: