Skip to content

Creating Database Models

A model is a Python class that represents a database table.

Example: User model

python
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)
 
    def __repr__(self):
        return f"<User {self.username}>"
python
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)
 
    def __repr__(self):
        return f"<User {self.username}>"

Key concepts

  • UserUser maps to a table (by default: useruser)
  • each attribute maps to a column
  • each instance maps to a row

Naming tables explicitly

python
class User(db.Model):
    __tablename__ = "users"
    # columns...
python
class User(db.Model):
    __tablename__ = "users"
    # columns...

This avoids surprises, especially in bigger projects.

Nullable vs required

  • nullable=Falsenullable=False means the DB will reject NULLs

In practice:

  • validate in forms (nice UX)
  • enforce at database level too (data integrity)

Visualize it

Here’s the relationship between the two models: one UserUser can own many PostPost rows.

diagram User and Post models mermaid
One-to-many relationship between User and Post

🧪 Try It Yourself

Exercise 1 – Create a Flask App

Exercise 2 – Dynamic Route

Exercise 3 – Return JSON

If this helped you, consider buying me a coffee ☕

Buy me a coffee

Was this page helpful?

Let us know how we did