版本: 2.0.36 当前版本 | 发布日期: 2024 年 10 月 15 日
SQLAlchemy 2.0 文档
- 向上: 主页
- 此页面
ORM 查询指南设置:列加载¶
本页说明了 列加载选项 文档中使用的映射和固定数据 ORM 查询指南.
>>> from typing import List
>>> from typing import Optional
>>>
>>> from sqlalchemy import Column
>>> from sqlalchemy import create_engine
>>> from sqlalchemy import ForeignKey
>>> from sqlalchemy import LargeBinary
>>> from sqlalchemy import Table
>>> from sqlalchemy import Text
>>> 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 User(Base):
... __tablename__ = "user_account"
... id: Mapped[int] = mapped_column(primary_key=True)
... name: Mapped[str]
... fullname: Mapped[Optional[str]]
... books: Mapped[List["Book"]] = relationship(back_populates="owner")
...
... def __repr__(self) -> str:
... return f"User(id={self.id!r}, name={self.name!r}, fullname={self.fullname!r})"
>>> class Book(Base):
... __tablename__ = "book"
... id: Mapped[int] = mapped_column(primary_key=True)
... owner_id: Mapped[int] = mapped_column(ForeignKey("user_account.id"))
... title: Mapped[str]
... summary: Mapped[str] = mapped_column(Text)
... cover_photo: Mapped[bytes] = mapped_column(LargeBinary)
... owner: Mapped["User"] = relationship(back_populates="books")
...
... def __repr__(self) -> str:
... return f"Book(id={self.id!r}, title={self.title!r})"
>>> engine = create_engine("sqlite+pysqlite:///:memory:", echo=True)
>>> Base.metadata.create_all(engine)
BEGIN ...
>>> conn = engine.connect()
>>> session = Session(conn)
>>> session.add_all(
... [
... User(
... name="spongebob",
... fullname="Spongebob Squarepants",
... books=[
... Book(
... title="100 Years of Krabby Patties",
... summary="some long summary",
... cover_photo=b"binary_image_data",
... ),
... Book(
... title="Sea Catch 22",
... summary="another long summary",
... cover_photo=b"binary_image_data",
... ),
... Book(
... title="The Sea Grapes of Wrath",
... summary="yet another summary",
... cover_photo=b"binary_image_data",
... ),
... ],
... ),
... User(
... name="sandy",
... fullname="Sandy Cheeks",
... books=[
... Book(
... title="A Nut Like No Other",
... summary="some long summary",
... cover_photo=b"binary_image_data",
... ),
... Book(
... title="Geodesic Domes: A Retrospective",
... summary="another long summary",
... cover_photo=b"binary_image_data",
... ),
... Book(
... title="Rocketry for Squirrels",
... summary="yet another summary",
... cover_photo=b"binary_image_data",
... ),
... ],
... ),
... ]
... )
>>> session.commit()
BEGIN ... COMMIT
>>> session.close()
>>> conn.begin()
BEGIN ...
© 版权 2007-2024,SQLAlchemy 作者和贡献者。
flambé! 龙和 炼金术士 图像设计由 Rotem Yaari 创建并慷慨捐赠。
使用 Sphinx 7.2.6 创建。文档最后生成时间: 2024 年 11 月 8 日星期五上午 08:41:19 EST