Labs ICT
โญ Pro Login

Defining Models

Creating database tables as Python classes.

Defining Models

Models are the heart of your database. They define what data you're storing and how it's structured. In Flask-SQLAlchemy, you create models by subclassing db.Model. Each model maps to a database table, and each attribute maps to a column. Think of it as writing a Python class that also happens to be a database schema.

Column Types

SQLAlchemy provides column types that match common database data types. You pick the one that fits your data best.

from datetime import datetime
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)
    bio = db.Column(db.Text, nullable=True)
    is_active = db.Column(db.Boolean, default=True)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)

Integer is for whole numbers, String(n) for text with a max length, Text for unlimited text, Boolean for true/false, and DateTime for dates and times. The primary_key=True means the id column uniquely identifies each row.

Relationships

Real data is connected. A user has posts, a post has comments. You define these connections with relationship().

class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(200), nullable=False)
    content = db.Column(db.Text, nullable=False)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    author = db.relationship('User', backref=db.backref('posts', lazy=True))

The ForeignKey links this column to the user.id column in the User table. The relationship() lets you access posts from a user object like user.posts, and the author from a post object like post.author.

Model Methods and Repr

You can add methods to your models just like any Python class. This is great for logic that belongs with the data. The __repr__ method makes debugging way easier because it gives you a useful string representation of your objects.

class User(db.Model):
    # ... columns ...

    def __repr__(self):
        return f'<User {self.username}>'

    def full_profile(self):
        return f'{self.username} ({self.email})'

Migrations with Flask-Migrate

As your app grows, you'll need to change your models โ€” add columns, rename fields, create new tables. Flask-Migrate (which wraps Alembic) tracks these changes and applies them to your database without losing data.

# Initialize migrations
flask db init

# Create a migration after model changes
flask db migrate -m "add user bio column"

# Apply the migration
flask db upgrade

Always use migrations in production. Running db.create_all() won't add new columns to existing tables โ€” migrations will.

Try it Yourself ->

๐Ÿงช Quick Quiz

How do you define a model?