How is inheritance of models implemented when defining ORM models in SQLAlchemy?
sobes.tech AI
Answer from AI
In SQLAlchemy, model inheritance is implemented using standard Python class inheritance, and different inheritance strategies can be used for database tables:
-
Single Table Inheritance (STI) — all fields of the base and derived classes are stored in one table, with the record type distinguished by a special column (discriminator).
-
Joined Table Inheritance — each class has its own table, with the child table containing only additional fields and referencing the base table via a foreign key.
-
Concrete Table Inheritance — each class has its own table with all fields, including those of the base class, without relationships between tables.
Example of simple inheritance with joined table inheritance:
from sqlalchemy import Column, Integer, String, ForeignKey
from sqlalchemy.orm import declarative_base, relationship
Base = declarative_base()
class Person(Base):
__tablename__ = 'person'
id = Column(Integer, primary_key=True)
name = Column(String)
type = Column(String)
__mapper_args__ = {
'polymorphic_identity': 'person',
'polymorphic_on': type
}
class Employee(Person):
__tablename__ = 'employee'
id = Column(Integer, ForeignKey('person.id'), primary_key=True)
employee_number = Column(String)
__mapper_args__ = {
'polymorphic_identity': 'employee',
}
Thus, model inheritance allows for convenient organization of data structure and logic in ORM.