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

Flask-SQLAlchemy — Designing Database Models

Flask-SQLAlchemy — Designing Database Models

In this chapter you will learn to define data models with Flask-SQLAlchemy, create SQLite database tables, and insert test data.


Why Use an ORM?

Writing SQL statements directly to operate the database is tedious and error-prone.

ORM (Object-Relational Mapping) lets you define table structures with Python classes and manipulate data with Python methods.

Flask-SQLAlchemy is the Flask-integrated version of SQLAlchemy, wrapping common operations and making configuration simpler.


Installation and Configuration



(venv) $ pip install flask-sqlalchemy

Example

File path: app.py

from

flask

import

Flask

from

flask_sqlalchemy

import

SQLAlchemy

app

=

Flask

(

name

)

SQLite database file path (located in the project root)

app.

config

[

'SQLALCHEMY_DATABASE_URI'

]

=

'sqlite:///blog.db'

Disable modification tracking (saves memory; will be disabled by default in future versions)

app.

config

[

'SQLALCHEMY_TRACK_MODIFICATIONS'

]

=

False

Create a db instance and bind it to the app

db

=

SQLAlchemy

(

app

)

sqlite:///blog.db The three slashes in it indicate a relative path. An SQLite database is just a file, requiring no database software installation, making it ideal for development and testing.


Define Models: Post and Category

Example

File path: models.py

from

datetime

import

datetime

from

app

import

db

class

Category

(

db.

Model

)

:

   

"""Article category"""

    tablename

=

'categories'

   

id

=

db.

Column

(

db.

Integer

,

primary_key

=

True

,

autoincrement

=

True

)

    name

=

db.

Column

(

db.

String

(

50

)

,

unique

=

True

,

nullable

=

False

)

    slug

=

db.

Column

(

db.

String

(

50

)

,

unique

=

True

,

nullable

=

False

)

   

backref: on a Category object, you can use .posts to reverse-query all its articles

    posts

=

db.

relationship

(

'Post'

,

backref

=

'category'

,

lazy

=

'dynamic'

)

   

def

repr

(

self

)

:

       

return

f

''

class

Post

(

db.

Model

)

:

   

"""Blog article"""

    tablename

=

'posts'

   

id

=

db.

Column

(

db.

Integer

,

primary_key

=

True

,

autoincrement

=

True

)

    title

=

db.

Column

(

db.

String

(

200

)

,

nullable

=

False

)

    slug

=

db.

Column

(

db.

String

(

200

)

,

unique

=

True

,

nullable

=

False

)

    summary

=

db.

Column

(

db.

Text

,

default

=

''

)

    content

=

db.

Column

(

db.

Text

,

nullable

=

False

)

   

Foreign key: db.ForeignKey('table_name.field_name')

    category_id

=

db.

Column

(

db.

Integer

,

db.

ForeignKey

(

'categories.id'

)

,

nullable

=

False

)

    created_at

=

db.

Column

(

db.

DateTime

,

default

=

datetime

.

utcnow

)

    updated_at

=

db.

Column

(

db.

DateTime

,

default

=

datetime

.

utcnow

,

onupdate

=

datetime

.

utcnow

)

   

def

repr

(

self

)

:

       

return

f

''

Common Field Types

Field type Database Type Common parameters
db.Integer INTEGER primary_key, autoincrement
db.String(N) VARCHAR(N) unique, nullable, default
db.Text TEXT default
db.DateTime DATETIME default, onupdate
db.Boolean BOOLEAN default
db.ForeignKey('table.field') FOREIGN KEY —

Creating a database table

Unlike Django's migrate, Flask requires you to initialize database tables manually.



(venv) $ flask shell                        # 进入 Flask 交互式 Shell

Example

In flask shell, enter

from

app

import

db

db.

create_all

(

)

   

Create database tables for all models

exit

(

)

After running it, a blog.db files.

db.create_all() It only creates tables that do not exist. If you modify the model structure (e.g., add a field), it will not automatically update the table. In production you should use Flask-Migrate (Chapter 5) to manage schema changes.


Insert Test Data with flask shell

Example

In flask shell, enter

from

app

import

db

from

models

import

Category

,

Post

1. Create a category

py_cat

=

Category

(

name

=

'Python'

,

slug

=

'python'

)

css_cat

=

Category

(

name

=

'CSS'

,

slug

=

'css'

)

flask_cat

=

Category

(

name

=

'Flask'

,

slug

=

'flask'

)

db.

session

.

add_all

(

[

py_cat

,

css_cat

,

flask_cat

]

)

db.

session

.

commit

(

)

2. Create an article

post1

=

Post

(

    title

=

'Complete Guide to Flask'

,

    slug

=

'flask-beginner-guide'

,

    summary

=

'Learn Flask from scratch, covering core concepts such as routing, templates, and ORM.'

,

    content

=

'

Why Learn Flask?

Flask is Python's most flexible web microframework...

'

,

    category

=

flask_cat

)

post2

=

Post

(

    title

=

'Python Coroutines Explained'

,

    slug

=

'python-coroutine'

,

    summary

=

'Understand asyncio, coroutines, and event loops in one article.'

,

    content

=

'

What is a coroutine?

A coroutine is a lighter concurrency approach than threads...

'

,

    category

=

py_cat

)

post3

=

Post

(

    title

=

'CSS Grid Layout in Practice'

,

    slug

=

'css-grid-layout'

,

    summary

=

'Easily implement complex responsive layouts with CSS Grid.'

,

    content

=

'

Getting Started with Grid

Grid is a two-dimensional layout system...

'

,

    category

=

css_cat

)

db.

session

.

add_all

(

[

post1

,

post2

,

post3

]

)

db.

session

.

commit

(

)

3. Verify queries

print

(

Post.

query

.

all

(

)

)

print

(

Post.

query

.

filter

(

Post.

category_id

==

1

)

.

all

(

)

)

Flask-SQLAlchemy Basic Queries

Method Equivalent SQL Return Value
Post.query.all() SELECT * FROM posts List
Post.query.get(1) WHERE id = 1 A single object or None
Post.query.get_or_404(1) WHERE id = 1 A single object or automatically returns 404
Post.query.filter_by(category_id=1).all() WHERE category_id=1 List
Post.query.filter(Post.title.ilike('%flask%')).all() WHERE title LIKE '%flask%' List
Post.query.order_by(Post.created_at.desc()).all() ORDER BY created_at DESC List

Chapter Summary

In this chapter you mastered the complete Flask-SQLAlchemy workflow: installing and configuring SQLALCHEMY_DATABASE_URI, defining models with db.Model (field types/foreign keys/relationship), initializing tables with db.create_all(), and inserting and querying data in flask shell.

At this point, the data structures for articles and categories have been established in the SQLite database.