Skip to content

Creating Database Models

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

Example: User model

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}>"
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

class User(db.Model):
    __tablename__ = "users"
    # columns...
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)

๐Ÿงช 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