Models help you organize and store data in your app. They act like blueprints for your data.
When you want to save user information like names and emails.
When you need to keep track of items in a store or inventory.
When you want to record blog posts or comments.
When you want to connect data, like users and their orders.
When you want to easily add, update, or delete data in your app.
Syntax
Flask
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class ModelName(db.Model):
id = db.Column(db.Integer, primary_key=True)
field_name = db.Column(db.String(100), nullable=False)
# add more fields as needed
Each model is a Python class that inherits from db.Model.
Fields are defined using db.Column with types like Integer or String.
Examples
This model stores users with unique usernames and emails.
Flask
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
This model stores blog posts with a title and content.
Flask
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(200), nullable=False)
content = db.Column(db.Text, nullable=False)
Sample Program
This example creates a simple Flask app with a User model. It adds one user named 'alice' and then prints the username.
Flask
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
with app.app_context():
db.create_all()
new_user = User(username='alice')
db.session.add(new_user)
db.session.commit()
user = User.query.first()
print(f'User: {user.username}')
OutputSuccess
Important Notes
Always call db.create_all() inside the app context to create tables.
Use nullable=False to make sure a field must have a value.
Unique fields prevent duplicate entries for that column.
Summary
Models define how data is stored in your app.
Each model is a class with fields as columns.
Use models to add, query, and manage data easily.
Practice
(1/5)
1. What is the main purpose of defining a model in a Flask application?
easy
A. To represent and manage data structure in the database
B. To create the user interface layout
C. To handle HTTP requests and responses
D. To style the web pages with CSS
Solution
Step 1: Understand what a model represents
A model in Flask defines how data is stored and structured in the database.
Step 2: Identify the role of models in the app
Models help manage data easily by mapping Python classes to database tables.
Final Answer:
To represent and manage data structure in the database -> Option A
Quick Check:
Model = Data structure representation [OK]
Hint: Models map classes to database tables for data storage [OK]
Common Mistakes:
Confusing models with UI components
Thinking models handle HTTP requests
Mixing models with styling or CSS
2. Which of the following is the correct way to define a model class named User with an integer primary key id in Flask-SQLAlchemy?
easy
A. class User():\n id = Column(Integer, primary_key=True)
B. class User(db.Model):\n id = Column(Integer)
C. def User(db.Model):\n id = db.Column(db.Integer, primary_key=True)
D. class User(db.Model):\n id = db.Column(db.Integer, primary_key=True)
Solution
Step 1: Check class definition syntax
Model classes inherit from db.Model in Flask-SQLAlchemy.
Step 2: Verify column definition
Columns use db.Column with type and primary key flag.
Final Answer:
class User(db.Model):\n id = db.Column(db.Integer, primary_key=True) -> Option D
Quick Check:
Model class inherits db.Model and uses db.Column [OK]
Hint: Model classes inherit db.Model; columns use db.Column [OK]
Common Mistakes:
Forgetting to inherit from db.Model
Using Column without db prefix
Defining model as a function instead of class
3. Given this model definition:
class Product(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50))
p = Product(id=1, name='Book')
print(p.name)
What will be the output?
medium
A. Product object
B. 1
C. Book
D. Error: missing __init__ method
Solution
Step 1: Understand model instance creation
Creating p = Product(id=1, name='Book') sets attributes directly.
Step 2: Check what print(p.name) outputs
It prints the name attribute value, which is 'Book'.
Final Answer:
Book -> Option C
Quick Check:
Accessing attribute prints its value [OK]
Hint: Instance attributes print their assigned values [OK]
Common Mistakes:
Assuming print shows object type
Expecting error due to no explicit __init__
Confusing id and name values
4. What is wrong with this model definition?
class Employee(db.Model):
id = db.Column(db.Integer)
name = db.Column(db.String, primary_key=True)
medium
A. db.String requires a length argument
B. Columns must be defined inside a method, not directly
C. Model class must have a __tablename__ attribute
D. Primary key should be on the id column, not name
Solution
Step 1: Check db.String usage
db.String requires a length argument like db.String(100).
Step 2: Verify other parts
Primary key can be on any column; __tablename__ is optional; columns are defined directly.
Final Answer:
db.String requires a length argument -> Option A
Quick Check:
db.String must have length [OK]
Hint: Always specify length in db.String(length) [OK]
Common Mistakes:
Assuming primary key must be id
Thinking __tablename__ is mandatory
Defining columns inside methods
5. You want to define a model Order with a composite primary key consisting of order_id (integer) and product_id (integer). Which is the correct way to define this in Flask-SQLAlchemy?
hard
A. class Order(db.Model):\n order_id = db.Column(db.Integer, primary_key=True)\n product_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
B. class Order(db.Model):\n order_id = db.Column(db.Integer)\n product_id = db.Column(db.Integer)\n __table_args__ = (db.PrimaryKeyConstraint('order_id', 'product_id'),)
C. class Order(db.Model):\n order_id = db.Column(db.Integer, primary_key=True)\n product_id = db.Column(db.Integer)
D. class Order(db.Model):\n order_id = db.Column(db.Integer)\n product_id = db.Column(db.Integer)
Solution
Step 1: Understand composite primary keys
Composite keys require defining multiple columns as primary keys together.
Step 2: Check Flask-SQLAlchemy syntax for composite keys
Use __table_args__ with db.PrimaryKeyConstraint listing columns.
Final Answer:
class Order(db.Model):\n order_id = db.Column(db.Integer)\n product_id = db.Column(db.Integer)\n __table_args__ = (db.PrimaryKeyConstraint('order_id', 'product_id'),) -> Option B
Quick Check:
Composite keys use __table_args__ with PrimaryKeyConstraint [OK]
Hint: Use __table_args__ with PrimaryKeyConstraint for composite keys [OK]
Common Mistakes:
Setting primary_key=True on multiple columns separately
Not using __table_args__ for composite keys
Defining only one column as primary key
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.