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

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来标识区分该记录属于哪个继承表.

原文链接:https://blog.csdn.net/wenxuansoft/article/details/50234007

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

上一篇:SQLSERVER:Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.


下一篇:JQ将数组转换为Json