VOOZH about

URL: https://www.geeksforgeeks.org/python/declaring-models-in-flask/

⇱ Declaring Models in Flask - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Declaring Models in Flask

Last Updated : 26 Mar, 2026

In Flask, models define the structure of data and handle database operations by mapping database tables to Python classes. ORM (Object Relational Mapping) is used which allows to interact with the database using Python code instead of writing SQL queries. Flask commonly uses SQLAlchemy as its ORM to manage data efficiently.

Creating Models using Flask-SQLAlchemy

To define models in Flask, we will use Flask-SQLAlchemy, which provides ORM support. Start by importing required modules and defining the create_app function to set up the application and initialize models.

Step 1: Install flask-sqlalchemy

Flask doesn't support ORM, but with the help of flask-sqlalchemy, we can achieve the ORM functionalities. Install flask-sqlalchemy extension (if not already installed) using:

pip install flask-sqlalchemy

Step 2: Import Necessary Modules

First we import the Flask and SQLAlchemy.

Step 3: Configure the Flask App and Database

Explanation:

  • SQLALCHEMY_DATABASE_URI: Specifies the database location (SQLite in this case).
  • SQLALCHEMY_TRACK_MODIFICATIONS: Disables unnecessary change tracking for better performance.

Step 4: Initialize the Database

Create a database object

Step 5: Define a Model

Now, we define a model, which represents a table in the database.

Explanation:

  • id: Auto-incrementing primary key.
  • date: Stores event timestamps (defaults to the current time).
  • event: Stores the event description, which cannot be null.

Step 6: Create the Database

Run the following inside an app context to generate the tables:

Explanation: This ensures all models are converted into database tables.

Step 7: Inserting Data into the Database

To add an event, create an instance of Event and commit it:

Explanation:

  • new_event = Event(event=event_description): Creates a new event with the given description.
  • db.session.add(new_event): Adds the new event to the database session.
  • db.session.commit(): Commits the transaction, saving the event permanently.

Step 8: Querying the database

We use db.session in SQLAlchemy to fetch and store data.

  • GET request: Fetches all events using db.session.execute(db.select(Event).order_by(Event.date)).scalars() and displays them.
  • POST request: Adds a new event to the database.

Explanation:

  • db.session.add() adds new event
  • db.session.commit() saves changes
  • db.select(Event) fetches events
  • order_by(Event.date) sorts by date

Flask app using Models

Let's build a simple Flask app "eventLog" where users can view and add events. The date and time are automatically stored when an event is added.

File structure

rootFolder
|_ eventLog
|_templates
| |_ home.html
|_app.py

app.py File

This application uses Flask-SQLAlchemy with SQLite to store events. We define a create_app function to configure the app, initialize the database and create the Event model. A route handles displaying and adding events and a CLI command is used to initialize the database.

home.html (Jinja Template)

This HTML code creates a simple webpage to display an event log with a table showing date-time and event details.

  • Jinja2 templating is used to loop through events from the Flask app and populate the table.
  • A form allows users to add new events with a text input and submit button.
  • An external "style.css" file is linked for styling.

Running the app

1. Activate the virtual environment:

venv\Scripts\activate

2. Create the database and tables:

flask init-db

3. Run the Flask app:

python app.py

This will start the app in debug mode at local host port 5000. Visit the following URL in browser:

http://127.0.0.1:5000/

Output

👁 event
Home page: displays all events
👁 event2
After adding event: new event appears in the list
👁 event3
Adding multiple events: events keep updating in the table
Comment