版本:2.0.36 当前版本 | 发布日期:2024 年 10 月 15 日
SQLAlchemy 2.0 文档
- 向上: 首页
- 本页内容
ORM 查询指南设置:单继承¶
本页演示了 单表继承 示例中使用的映射和固定数据,这些示例位于 为继承映射编写 SELECT 语句 文档中,该文档属于 ORM 查询指南。
>>> 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 ...
© 版权 2007-2024,SQLAlchemy 作者和贡献者。
flambé! 龙和 炼金术士 图像设计由 Rotem Yaari 创建并慷慨捐赠。
使用 Sphinx 7.2.6 创建。文档最后生成时间:2024 年 11 月 8 日星期五 上午 8:41:19 EST