Creating Database Models
A model is a Python class that represents a database table.
Example: User model
Section titled “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}>"Key concepts
Section titled “Key concepts”Usermaps to a table (by default:user)- each attribute maps to a column
- each instance maps to a row
Naming tables explicitly
Section titled “Naming tables explicitly”class User(db.Model):
__tablename__ = "users"
# columns...This avoids surprises, especially in bigger projects.
Nullable vs required
Section titled “Nullable vs required”nullable=Falsemeans the DB will reject NULLs
In practice:
- validate in forms (nice UX)
- enforce at database level too (data integrity)
Visualize it
Section titled “Visualize it”Here’s the relationship between the two models: one User can own many Post rows.
classDiagram
class User {
id
username
email
}
class Post {
id
title
body
user_id
}
User "1" --> "*" Post
🧪 Try It Yourself
Section titled “🧪 Try It Yourself”Exercise 1 – Create a Flask App
Section titled “Exercise 1 – Create a Flask App”Exercise 2 – Dynamic Route
Section titled “Exercise 2 – Dynamic Route”Exercise 3 – Return JSON
Section titled “Exercise 3 – Return JSON”pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading