理解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

posted on   不要挡着我晒太阳  阅读(447)  评论(0编辑  收藏  举报

编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示