Skip to main content

Creating Models

A Model is a Python class that SQLAlchemy maps to a database table.
Each:
  • Model represents a table
  • Model object represents a row
  • Attribute represents a column
Example:
Every model inherits from Base.

__tablename__

__tablename__ specifies the database table name.

Naming Convention

  • Model names are usually PascalCase and singular.
  • Table names are usually snake_case and plural.

Mapped

Mapped declares an attribute as a mapped database column.
Mapped only declares the attribute. The column configuration is done using mapped_column().

mapped_column()

mapped_column() creates and configures the database column.
Initially, it can be used without any arguments.
Additional options can be provided later.

SQLAlchemy Data Types

SQLAlchemy automatically maps Python types to database types. SQLAlchemy-specific types are used when additional configuration is required.

Common Data Types

String Types

Numeric Types

Numeric(10, 2) means:
  • 10 → Total digits
  • 2 → Digits after the decimal point

Date and Time Types

Other Types

Common Column Constraints

Constraints define rules for the data stored in a column.

Complete Model

Model Representation

ForeignKey

A Foreign Key creates a link between two database tables. It is used when one table refers to a record in another table.
In this example:
  • course_id is a column in the current table.
  • "courses.id" refers to the id column of the courses table.

Relationships

ForeignKey establishes the database-level relationship. The relationship() function is used to access related objects in Python and will be discussed in the Relationships chapter.

Key Points

  • ForeignKey links one table to another.
  • It references the primary key of another table.
  • It helps maintain referential integrity.
  • It is commonly used in one-to-one, one-to-many, and many-to-many relationships.

Quick Revision