0
0
Flaskframework~5 mins

Creating tables (db.create_all) in Flask

Choose your learning style9 modes available
Introduction

We use db.create_all() to make the database tables based on the models we defined. It sets up the structure so we can store data.

When starting a new Flask app and you want to create the database tables for the first time.
After adding new models or changing existing ones and you want to create missing tables.
When testing locally and you want a quick way to set up the database structure.
Before running your app to ensure the database has the right tables.
Syntax
Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
db = SQLAlchemy(app)

# Create all tables based on models

db.create_all()

This command creates tables only if they do not exist yet.

It does not update or delete existing tables or columns.

Examples
Creates all tables defined by your SQLAlchemy models in the current database.
Flask
db.create_all()
Runs create_all() inside the Flask app context, which is needed if you run it outside request handling.
Flask
with app.app_context():
    db.create_all()
Sample Program

This example creates a simple Flask app with one model User. It then calls db.create_all() inside the app context to create the User table in a SQLite database file named test.db. Finally, it prints a success message.

Flask
from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50), nullable=False)

with app.app_context():
    db.create_all()

print('Tables created successfully!')
OutputSuccess
Important Notes

Always run db.create_all() inside the Flask app context to avoid errors.

This method only creates tables if they don't exist; it won't update existing tables.

For database schema changes, consider using migration tools like Flask-Migrate.

Summary

db.create_all() makes tables in the database from your models.

Run it inside the Flask app context to work properly.

It creates missing tables but does not change existing ones.