I have the following objects and relations defined. This is actually quite a simple case, and I am providing all those fields just to show why I believe inhalation and injection anesthesia should be defined by two different classes.
class InhalationAnesthesia(Base):
__tablename__ = "inhalation_anesthesias"
id = Column(Integer, primary_key=True)
anesthetic = Column(String)
concentration = Column(Float)
concentration_unit = Column(String)
duration = Column(Float)
duration_unit = Column(String)
class TwoStepInjectionAnesthesia(Base):
__tablename__ = "twostep_injection_anesthesias"
id = Column(Integer, primary_key=True)
anesthetic = Column(String)
solution_concentration = Column(Float)
solution_concentration_unit = Column(String)
primary_dose = Column(Float)
primary_rate = Column(Float)
primary_rate_unit = Column(String)
secondary_rate = Column(Float)
secondary_rate_unit = Column(String)
class Operation(Base):
__tablename__ = "operations"
id = Column(Integer, primary_key=True)
anesthesia_id = Column(Integer, ForeignKey('inhalation_anesthesias.id'))
anesthesia = relationship("InhalationAnesthesia", backref="used_in_operations")
I would, however, like to define the anesthetic attribute of the Operation
class in such a way that any Operation
object can point to either a TwoStepInjectionAnesthesia
object or an InhalationAnesthesia
object.
How can I do that?
I suggest you to use inheritance. It's very, very well explained in SqlAlchemy docs here and here
My recommendation is to create an
Anesthesia
class and make bothInhalationAnesthesia
andTwoStepInjectionAnesthesia
inherit from it. It's your call to decide which type of table inheritance use:For your case I'm asuming joined table inheritance is the election:
The purpose of
discriminator
field:__mapper_args__
's polymorphic_on key define which field use as discriminator. In children classes (below), polymorphic_identity key define the value that will be stored in the polymorphic discriminator column for instances of the class.Finally the
Operation
class may reference the parent tableAnesthesia
with a typical relationship:Hope this is what you're looking for.