我建议你使用继承。 SqlAlchemy 文档中对此进行了非常非常好的解释here http://docs.sqlalchemy.org/en/rel_1_0/orm/inheritance.html and here http://docs.sqlalchemy.org/en/rel_1_0/orm/extensions/declarative/inheritance.html#declarative-inheritance
我的建议是创建一个Anesthesia
类并同时进行InhalationAnesthesia
and TwoStepInjectionAnesthesia
继承它。您可以决定使用哪种类型的表继承:
最常见的继承形式是单表和连接表,
而具体的继承则带来了更多的配置挑战。
对于你的情况我假设连接表继承是选举:
class Anesthesia(Base)
__tablename__ = 'anesthesias'
id = Column(Integer, primary_key=True)
anesthetic = Column(String)
# ...
# every common field goes here
# ...
discriminator = Column('type', String(50))
__mapper_args__ = {'polymorphic_on': discriminator}
的目的discriminator
field:
...是充当鉴别器,并存储
指示行中表示的对象类型的值。
该列可以是任何数据类型,但字符串和整数是
最常见的。
__mapper_args__
's 多态性key 定义使用哪个字段作为鉴别器。
在儿童班(下)中,多态身份key 定义将存储在类实例的多态鉴别器列中的值。
class InhalationAnesthesia(Anesthesia):
__tablename__ = 'inhalation_anesthesias'
__mapper_args__ = {'polymorphic_identity': 'inhalation'}
id = Column(Integer, ForeignKey('anesthesias.id'), primary_key=True)
# ...
# specific fields definition
# ...
class TwoStepInjectionAnesthesia(Anesthesia):
__tablename__ = 'twostep_injection_anesthesias'
__mapper_args__ = {'polymorphic_identity': 'twostep_injection'}
id = Column(Integer, ForeignKey('anesthesias.id'), primary_key=True)
# ...
# specific fields definition
# ...
最后Operation
类可以引用父表Anesthesia
具有典型的关系:
class Operation(Base):
__tablename__ = 'operations'
id = Column(Integer, primary_key=True)
anesthesia_id = Column(Integer, ForeignKey('anesthesias.id'))
anesthesia = relationship('Anesthesia', backref='used_in_operations')
希望这就是您正在寻找的。