0Pricing
Python Academy · Lesson

Defining Models

Map classes to tables.

Models Map to Tables

In the SQLAlchemy ORM, a model is a Python class that maps to a database table. Each instance becomes a row.

Models inherit from a shared Base class.

from sqlalchemy.orm import DeclarativeBase
class Base(DeclarativeBase):
    pass
print('Base class ready')

The __tablename__

Every model sets __tablename__ to name its table. SQLAlchemy uses this when generating SQL.

from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
class Base(DeclarativeBase):
    pass
class User(Base):
    __tablename__ = 'users'
    id: Mapped[int] = mapped_column(primary_key=True)
print(User.__tablename__)

All lessons in this course

  1. SQLAlchemy Core vs ORM
  2. Defining Models
  3. Querying with the Session
  4. Relationships and Joins
← Back to Python Academy