I'm having a hard time using foreign key references for inheritance in SQLAlchemy.
I have a drives table that looks like this with id as the primary key:
Column | Type | Collation | Nullable | Default
---------------+-----------------------+-----------+----------+------------------------------------
id | integer | | not null | nextval('drives_id_seq'::regclass)
model | integer | | not null |
I also have another table called smart that looks like this with <ts, drive> as a primary key and drive is a foreign key referencing drives.id:
Column | Type | Collation | Nullable | Default
---------------+-----------------------+-----------+----------+------------------------------------
drive | integer | | not null | nextval('drives_id_seq'::regclass)
ts | timestamp without timezone | | not null |
value | integer | | |
I have the following class definitions to represent the above tables.
class Drives(Base):
__tablename__ = 'drives'
id = Column('id', Integer, primary_key=True)
model = Column('model', String)
class Smart(Base):
___tablename__ = 'smart'
drive = Column('drive', Integer, ForeignKey=Drives.id)
ts = Column('ts', TIMESTAMP)
value = Column('value', Integer)
drives = relationship('Drives')
# I would like something like the following to work, but I get an AttributeError for `model`
__mapper_args__ = {'primary_key': [ts, drive], 'polymorphic_on': drives.model}
I would like to create two derived classes ModelASmart or ModelBSmart where smart.value is interpreted differently based on the model corresponding to the drive.
class ModelASmart(Smart):
__mapper_args__ = {'polymorphic_identity': 'ModelA', 'primary_key': [Smart.ts, Smart.drive]}
@hybrid_property
def actual_value(self):
return self.value * 2
class ModelBSmart(Smart):
__mapper_args__ = {'polymorphic_identity': 'ModelB', 'primary_key': [Smart.ts, Smart.drive]}
@hybrid_property
def actual_value(self):
return self.value * 3
My question: How do I refer to a column (model) from another table (drives) as a discriminator in the main table smart?