Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

SQLAlchemy Models — Designing Database Tables

SQLAlchemy Models — Designing Database Tables

In this chapter you will learn to define data models with native SQLAlchemy ORM and manage database sessions through FastAPI dependency injection.


Why Doesn't FastAPI Use a Built-in ORM?

Django has a built-in ORM, and Flask recommends Flask-SQLAlchemy.

FastAPI has no built-in ORM — it wants you to choose the most suitable tool; SQLAlchemy + Pydantic is the community-recognized best combination.



(venv) $ pip install sqlalchemy


Configure the Database Connection

Example

File path: database.py

from

sqlalchemy

import

create_engine

from

sqlalchemy.

orm

import

sessionmaker

,

DeclarativeBase

SQLite database file path

SQLALCHEMY_DATABASE_URL

=

"sqlite:///./blog.db"

Create the engine: check_same_thread is a SQLite-specific parameter

engine

=

create_engine

(

    SQLALCHEMY_DATABASE_URL

,

    connect_args

=

{

"check_same_thread"

:

False

}

 

SQLite-specific: allow cross-thread usage

)

Create the session factory

SessionLocal

=

sessionmaker

(

autocommit

=

False

,

autoflush

=

False

,

bind

=

engine

)

Base class: all ORM models inherit from it

class

Base

(

DeclarativeBase

)

:

   

pass

check_same_thread=False is a necessary configuration for SQLite in FastAPI. By default SQLite does not allow using the same connection across threads, but in a web application each request may be handled in a different thread.

Dependency injection: get_db

Example

File path: appended to database.py

from

fastapi

import

Depends

def

get_db

(

)

:

   

"""FastAPI dependency injection: create an independent database session for each request"""

    db

=

SessionLocal

(

)

   

try

:

       

yield

db          

Use this session during the request

   

finally

:

        db.

close

(

)

       

Automatically close the session after the request to prevent connection leaks

Depends(get_db) is FastAPI's dependency injection system; route functions automatically obtain a database session through dependency injection.


Define Models: Post and Category

Example

File path: models.py

from

sqlalchemy

import

Column

,

Integer

,

String

,

Text

,

DateTime

,

ForeignKey

from

sqlalchemy.

orm

import

relationship

from

datetime

import

datetime

from

database

import

Base

class

Category

(

Base

)

:

   

"""Article category"""

    tablename

=

"categories"

   

id

=

Column

(

Integer

,

primary_key

=

True

,

index

=

True

)

    name

=

Column

(

String

(

50

)

,

unique

=

True

,

nullable

=

False

)

    slug

=

Column

(

String

(

50

)

,

unique

=

True

,

nullable

=

False

)

   

back_populates bidirectional relationship

    posts

=

relationship

(

"Post"

,

back_populates

=

"category"

)

class

Post

(

Base

)

:

   

"""Blog article"""

    tablename

=

"posts"

   

id

=

Column

(

Integer

,

primary_key

=

True

,

index

=

True

)

    title

=

Column

(

String

(

200

)

,

nullable

=

False

)

    slug

=

Column

(

String

(

200

)

,

unique

=

True

,

nullable

=

False

)

    summary

=

Column

(

Text

,

default

=

""

)

    content

=

Column

(

Text

,

nullable

=

False

)

    category_id

=

Column

(

Integer

,

ForeignKey

(

"categories.id"

)

,

nullable

=

False

)

    created_at

=

Column

(

DateTime

,

default

=

datetime

.

utcnow

)

    updated_at

=

Column

(

DateTime

,

default

=

datetime

.

utcnow

,

onupdate

=

datetime

.

utcnow

)

   

Bidirectional relationship with Category

    category

=

relationship

(

"Category"

,

back_populates

=

"posts"

)

What is used in FastAPI is native SQLAlchemy(not Flask-SQLAlchemy's db.Model). Note: the differences in Column import, Base inheritance, and relationship syntax. A comparison table will follow.


Initialize Database Tables

Example

File path: create tables in the startup event of main.py

from

fastapi

import

FastAPI

from

database

import

engine

,

Base

from

models

import

Category

,

Post  

Ensure the model classes are imported so that Base.metadata can recognize them

app

=

FastAPI

(

)

@

app.

on_event

(

"startup"

)

def

on_startup

(

)

:

   

"""Automatically create database tables on application startup (development only)"""

    Base.

metadata

.

create_all

(

bind

=

engine

)

Later we will switch to Alembic migrations (Chapter 6),create_all only used during rapid prototyping.


Insert test data

Insert test data in a Python script:

Example

File path: seed.py (only needs to be run once)

from

database

import

SessionLocal

from

models

import

Category

,

Post

db

=

SessionLocal

(

)

Create categories

py

=

Category

(

name

=

"Python"

,

slug

=

"python"

)

css

=

Category

(

name

=

"CSS"

,

slug

=

"css"

)

fastapi

=

Category

(

name

=

"FastAPI"

,

slug

=

"fastapi"

)

db.

add_all

(

[

py

,

css

,

fastapi

]

)

db.

commit

(

)

Create posts

db.

add_all

(

[

    Post

(

title

=

"The Complete Guide to FastAPI"

,

slug

=

"fastapi-guide"

,

         summary

=

"Learn FastAPI from Scratch"

,

content

=

"

Why Choose FastAPI?

...

"

,

         category_id

=

fastapi.

id

)

,

    Post

(

title

=

"Python Coroutines Explained"

,

slug

=

"python-coroutine"

,

         summary

=

"Understanding asyncio"

,

content

=

"

What is a coroutine?

...

"

,

         category_id

=

py.

id

)

,

    Post

(

title

=

"CSS Grid Layout in Practice"

,

slug

=

"css-grid"

,

         summary

=

"Implementing Responsive Layout with Grid"

,

content

=

"

Getting Started with Grid

...

"

,

         category_id

=

css.

id

)

,

]

)

db.

commit

(

)

db.

close

(

)

print

(

"Test data inserted successfully!"

)

Run python seed.py, inserting 3 posts into the database.


ORM Syntax Comparison Across Four Frameworks

Operation Django Flask-SQLAlchemy FastAPI (native SQLAlchemy)
base class models.Model db.Model Base (DeclarativeBase)
Field models.CharField() db.Column(...) Column(...)
Foreign key ForeignKey(to, on_delete) db.ForeignKey('table.col') ForeignKey('table.col')
Relational Automatic reverse db.relationship + backref relationship + back_populates
Session Automatic management db.session SessionLocal() + Depends

Chapter Summary

In this chapter you mastered SQLAlchemy integration in FastAPI: create_engine + SessionLocal to configure the database connection, DeclarativeBase to define the model base class, get_db dependency injection to manage sessions, and Column/relationship to define fields and relationships.

Compared with Flask-SQLAlchemy, native SQLAlchemy requires slightly more code but is completely open-source and controllable.