Release: 2.1.0b1
in development
| Release Date: not released yet
SQLAlchemy 2.1 Documentation
- Up: Home
- On this page:
Setup for ORM Queryguide: Single Inheritance¶
This page illustrates the mappings and fixture data used by the Single Table Inheritance examples in the Writing SELECT statements for Inheritance Mappings document of the ORM Querying Guide.
>>> from sqlalchemy import create_engine
>>> from sqlalchemy import ForeignKey
>>> from sqlalchemy.orm import DeclarativeBase
>>> from sqlalchemy.orm import Mapped
>>> from sqlalchemy.orm import mapped_column
>>> from sqlalchemy.orm import relationship
>>> from sqlalchemy.orm import Session
>>>
>>>
>>> class Base(DeclarativeBase):
... pass
>>> class Employee(Base):
... __tablename__ = "employee"
... id: Mapped[int] = mapped_column(primary_key=True)
... name: Mapped[str]
... type: Mapped[str]
...
... def __repr__(self):
... return f"{self.__class__.__name__}({self.name!r})"
...
... __mapper_args__ = {
... "polymorphic_identity": "employee",
... "polymorphic_on": "type",
... }
>>> class Manager(Employee):
... manager_name: Mapped[str] = mapped_column(nullable=True)
... __mapper_args__ = {
... "polymorphic_identity": "manager",
... }
>>> class Engineer(Employee):
... engineer_info: Mapped[str] = mapped_column(nullable=True)
... __mapper_args__ = {
... "polymorphic_identity": "engineer",
... }
>>>
>>> engine = create_engine("sqlite://", echo=True)
>>>
>>> Base.metadata.create_all(engine)
BEGIN ...
>>> conn = engine.connect()
>>> from sqlalchemy.orm import Session
>>> session = Session(conn)
>>> session.add_all(
... [
... Manager(
... name="Mr. Krabs",
... manager_name="Eugene H. Krabs",
... ),
... Engineer(name="SpongeBob", engineer_info="Krabby Patty Master"),
... Engineer(
... name="Squidward",
... engineer_info="Senior Customer Engagement Engineer",
... ),
... ],
... )
>>> session.commit()
BEGIN ...
© Copyright 2007-2024, the SQLAlchemy authors and contributors.
flambé! the dragon and The Alchemist image designs created and generously donated by Rotem Yaari.
Created using Sphinx 7.2.6. Documentation last generated: Fri 08 Nov 2024 08:32:22 AM EST