Skip to content

Creating Database Models

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

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}>"
  • User maps to a table (by default: user)
  • each attribute maps to a column
  • each instance maps to a row
python
class User(db.Model):
    __tablename__ = "users"
    # columns...

This avoids surprises, especially in bigger projects.

  • nullable=False means the DB will reject NULLs

In practice:

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

Here’s the relationship between the two models: one User can own many Post rows.

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

pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading