Creating Models
A Model is a Python class that SQLAlchemy maps to a database table.- Model represents a table
- Model object represents a row
- Attribute represents a column
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.
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 digits2→ 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.course_idis a column in the current table."courses.id"refers to theidcolumn of thecoursestable.
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
ForeignKeylinks 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.