Last modified: Jun 11, 2025 By Alexander Williams

Install Flask-SQLAlchemy in Python - Quick Guide

Flask-SQLAlchemy is a Flask extension that simplifies database integration. It combines Flask with SQLAlchemy for easy database management.

Prerequisites

Before installing Flask-SQLAlchemy, ensure you have Python and Flask installed. You can check using:


python --version
flask --version

If Flask is not installed, use pip install flask. For more Flask extensions, check Install Flask-WTF in Python.

Install Flask-SQLAlchemy

Use pip to install Flask-SQLAlchemy:


pip install flask-sqlalchemy

This installs the latest version. Verify the installation with:


pip show flask-sqlalchemy

Basic Setup

Create a Flask app and configure Flask-SQLAlchemy:


from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
db = SQLAlchemy(app)

The SQLALCHEMY_DATABASE_URI specifies the database. Here, it's SQLite.

Define a Model

Create a simple model for demonstration:


class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(20), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)

    def __repr__(self):
        return f"User('{self.username}', '{self.email}')"

This creates a User model with id, username, and email fields.

Create the Database

Initialize the database with Flask shell:


flask shell

Then run:


db.create_all()

This creates the database file. For migrations, see Install Flask-Migrate.

CRUD Operations

Perform basic operations:


# Create
user1 = User(username='john', email='john@example.com')
db.session.add(user1)
db.session.commit()

# Read
users = User.query.all()

# Update
user1.email = 'new@example.com'
db.session.commit()

# Delete
db.session.delete(user1)
db.session.commit()

These commands handle create, read, update, and delete operations.

Common Issues

If you face errors, check:

- Flask-SQLAlchemy version compatibility.

- Database URI correctness.

- Proper model definitions.

For timezone issues, refer to Install pytz in Python.

Conclusion

Flask-SQLAlchemy simplifies database management in Flask apps. It integrates SQLAlchemy for powerful queries. Follow this guide to get started.

For more Flask extensions, explore our other guides. Happy coding!