<p>选择如何表示继承主要是一个数据库设计问题。对于性能来说,单表继承通常是最好的。从一个好的数据库设计角度来看,连接表继承更好。联接表继承使您能够拥有数据库强制执行的子类的外键,对于子类字段具有非空约束要简单得多。具体的表继承是两个世界中最糟糕的。</p>
<p>具有声明性的单表继承设置如下所示:</p>
<pre><code>class Building(Base):
__tablename__ = 'building'
id = Column(Integer, primary_key=True)
building_type = Column(String(32), nullable=False)
x = Column(Float, nullable=False)
y = Column(Float, nullable=False)
__mapper_args__ = {'polymorphic_on': building_type}
class Commercial(Building):
__mapper_args__ = {'polymorphic_identity': 'commercial'}
business = Column(String(50))
class Residential(Building):
__mapper_args__ = {'polymorphic_identity': 'residential'}
num_residents = Column(Integer)
</code></pre>
<p>要使它成为联接表继承,需要添加</p>
<pre><code>__tablename__ = 'commercial'
id = Column(None, ForeignKey('building.id'), primary_key=True)
</code></pre>
<p>到子类。</p>
<p>两种方法的查询基本相同:</p>
<pre><code># buildings that are within x>5 and y>3
session.query(Building).filter((Building.x > 5) & (Building.y > 3))
# Residential buildings that have only 1 resident
session.query(Residential).filter(Residential.num_residents == 1)
</code></pre>
<p>要控制加载哪些字段,可以使用<code>query.with_polymorphic()</code>方法。</p>
<p>考虑对数据映射使用继承的最重要的事情是,您是否真的需要继承,或者可以使用聚合。如果你需要改变建筑物的类型,或者你的建筑物可以有商业和住宅两个方面,继承将是一个痛苦。在这些情况下,最好将商业和住宅方面作为相关对象。</p>