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
UserUsermaps 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=Falsemeans 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.
classDiagram
class User {
id
username
email
}
class Post {
id
title
body
user_id
}
User "1" --> "*" 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 coffeeWas this page helpful?
Let us know how we did
