Setting Up Flask ORM with SQLAlchemy and Database Migrations

To use an ORM in Flask, install the required packages:

pip3 install sqlalchemy flask-sqlalchemy

Create a MySQL database for your application:

CREATE DATABASE flask DEFAULT CHARSET utf8 COLLATE utf8_general_ci;

Configure the database URI in your Flask app:

app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:123456@localhost:3306/flask'

Initialize the SQLAlchemy extension:

from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy(app)

Define models by subclassing db.Model. Each class represents a table:

class User(db.Model):
    __tablename__ = 'users'  # Optional; defaults to lowercase class name
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    email = db.Column(db.String(120), index=True, default='')

Common column types include:

  • Integerint
  • String(size)str
  • Textstr
  • Booleanbool
  • DateTimedatetime.datetime
  • Floatfloat

Column options:

  • primary_key=True: marks as primary key
  • autoincrement=True: enables auto-increment
  • unique=True: enforces uniqueness
  • nullable=False: disallows NULL values
  • index=True: adds a database index
  • default=value: sets a default value

For managing schema changes, use Flask-Migrate instead of db.create_all() or db.drop_all().

Set up migration support:

from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand

manager = Manager(app)
migrate = Migrate(app, db)
manager.add_command('db', MigrateCommand)

Run these commands once to initialize migrations:

python3 app.py db init

Generate a migration script after modifying models:

python3 app.py db migrate -m "Add user table"

Apply the migration to the daatbase:

python3 app.py db upgrade

Tags: Flask SQLAlchemy ORM database migration

Posted on Thu, 18 Jun 2026 16:52:43 +0000 by sunnypal