Skip to content
tezvyn:
Menu

SQLAlchemy Declarative: Python Classes as Database Tables

Source: docs.sqlalchemy.orgEasyHow cards are made

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').

Interview question

According to the card, what is the primary role of SQLAlchemy's Declarative mapping in a "code-first" development approach?

  • a.To convert raw SQL statements into Python object instances.
  • b.To define database table structures directly within Python classes.Correct
  • c.To provide a mechanism for executing database-specific stored procedures.
  • d.To generate SQL queries from existing database tables.
Why?

The card states Declarative mapping is ideal for "code-first" development where Python code is the source of truth for the database schema, allowing developers to define tables as Python classes. Option D describes reflection, which is the opposite direction (database to Python classes), not the primary role of Declarative mapping for new applications.

Just read this? Test yourself on what you have been reading.

Read the original → docs.sqlalchemy.org

Put your scrolling time to good use

Learn one idea, try a quiz and save useful cards for revision. Tezvyn makes it easy to learn and stay current in your tech field, a few minutes at a time.

The iPhone app is on the way

We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.

Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.

Get it on Google PlayiPhone app coming soon

We are hiring for this. Every open role lists the topics its interview covers, so you can prepare for the real thing rather than guessing.

See open roles