tezvyn:

SQLAlchemy Declarative: Python Classes as Database Tables

AI-drafted, machine-checkedSource: docs.sqlalchemy.orgbeginner

SQLAlchemy's Declarative Mapping lets you define database tables as Python classes. You write a class with typed attributes, and SQLAlchemy generates the SQL. It's the standard way to use the ORM, turning database rows into Python objects.

WHY IT EXISTS To bridge the gap between object-oriented Python code and relational database tables. Instead of writing SQL strings and manually parsing results, developers can work with familiar Python objects, letting the Object Relational Mapper (ORM) handle the complex and error-prone translation.

THE MENTAL MODEL Think of a declarative model as a blueprint for a database table, written in Python. You define a class User with attributes id and name. SQLAlchemy reads this blueprint and understands how to create a users table and how to translate a User(name="Alice") object into an INSERT statement.

HOW IT WORKS You create a base class using DeclarativeBase. Your model classes then inherit from this base. Inside your model, you define columns as class attributes using mapped_column() and Python's Mapped type hints, for example: name: Mapped[str]. When your application starts, SQLAlchemy inspects these class definitions and builds the necessary internal Table and Mapper objects that represent the database schema and the class-to-table mapping.

WHEN TO USE IT This is the primary and recommended style for all new applications using the SQLAlchemy ORM. It's ideal for "code-first" development where your Python code is the source of truth for your database schema. It integrates cleanly with modern Python features like type hints and dataclasses.

WHEN NOT TO USE IT For simple scripts that only need to run a few raw SQL queries, the ORM can be overkill. If you have a complex, pre-existing database and don't want to write out all the models by hand, you might use SQLAlchemy's reflection tools to auto-generate the declarative models from the database schema.

ONE CANONICAL EXAMPLE A simple User model. You define a class: class User(Base): __tablename__ = 'users'; id: Mapped[int] = mapped_column(primary_key=True); name: Mapped[str]. When you create an instance user1 = User(name='sandy'), it's just a Python object. To save it, you must add it to a session and commit: session.add(user1); session.commit(). SQLAlchemy translates this into an INSERT INTO users (name) VALUES ('sandy').

Read the original → docs.sqlalchemy.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.