Part 2: Building a User-Friendly Todo App with Flask - A Step-by-Step Guide for setting up our models with foreign key relationships
Hey folks, welcome to part two of our Building a User-Friendly Todo App with Flask! In this installment, we're diving into setting up our models with foreign key relationships, setting up environment variables and creating a new local PostgreSQL database using the pgAdmin application. Let's get started!
Setting up Models with ForeignKey Relationships
Creating Models in models.py
In your models.py file, let's create two models: Category and Todo.
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.orm import relationship
from sqlalchemy import ForeignKeyConstraint
db = SQLAlchemy()
#add this part
class Category(db.Model):
__tablename__ = 'Category'
id = db.Column(db.Integer, primary_key = True)
name = db.Column(db.String(), nullable=False)
todos = relationship('Todo', cascade='all, delete-orphan')
def __repr__(self):
return f'<Category {self.id} {self.name}'
class Todo(db.Model):
__tablename__ = 'Todo'
id = db.Column(db.Integer, primary_key = True)
description = db.Column(db.String(), nullable=False)
category = db.Column(db.Integer, db.ForeignKey('Category.id'), nullable=False)
__table_args__ = (
ForeignKeyConstraint(['category'], ['Category.id'], ondelete='CASCADE'),
)
def __repr__(self):
return f'<Todo {self.id} {self.description}'
Explaining the Models
Category Model:
The Category model contains three fields:
- id: Acts as a unique identifier or primary key for our category items.
- name: A simple string field accepting the name of our category.
- todos: This field establishes a reverse relationship to the Todo model, specifying actions to take on all associated todos when a category is deleted. In this case, it's set to delete all associated todos.
Todo Model:
The Todo model includes:
- id: Serves as a unique identifier or primary key for our todo items.
- description: A string field containing the task description for a todo item.
- category: A foreign key relationship linked to the Category model. This means that each todo item is linked to only one category, while a category can be connected to multiple todo items.
Understanding the Methods:
__repr__ Method: This method generates a string representation of the object for easier debugging and logging purposes. It helps in identifying and understanding instances of the classes when printed or used in logs or error messages.
With these models set up, we've completed a crucial step in our todo application development. For a detailed walkthrough, check out the video tutorial below.
Setting up Environment Variables in Flask:
I already wrote an article on how you can setup environment variables in your flask application, so go to link link to learn how to set one up.
Creating a Local Postgresql database on pc:
Check out the tutorial in this link to learn how you can download and setup pgadmin 4 on your pc so you can use it to create postgresql database instances.
Connecting the local Postgresql database to your flask application:
Once you have setup your local postgresql database connection, what you need to do is to migrate your database models and you can accomplish that by following the steps below
First before you start go to your config.py file and set your new database url to the SQLALCHEMY_DATABASE_URI parameter as shown below
SQLALCHEMY_DATABASE_URI = "postgresql://postgres:2123@localhost:5432/flask-todo"
and then go to app.py and uncomment the configuration setup as shown below
from flask import Flask, render_template, request, redirect, url_for, flash, jsonify
from models import db, Todo, Category
from flask_migrate import Migrate
app = Flask(__name__)
app.config.from_object('config')
app.app_context().push()
db.init_app(app)
migrate = Migrate(app, db)
Step 1: setup flask in your terminal by executing this in your terminal
For Windows PowerShell:
set FLASK_APP=app.py
For Windows CMD:
$env:FLASK_APP = "app.py"
For macOS/Linux:
export FLASK_APP=app.py
Step 2: Intialize your database migrations by executing the command below
flask db init
Flask db init: This command might be used in some Flask extensions or projects to initialize the database, particularly if the project uses Flask-SQLAlchemy or Flask-Migrate. It's often a custom command implemented by the developer or included as part of the project's setup to create the necessary database tables or perform other initializations related to the database
Step 3: Create your migration script by executing the command below
flask db migrate
Flask db migrate: This command is used to generate a migration script. When changes are made to the structure of the database models (like adding a new table, changing a column's data type, etc.), Flask-Migrate helps create a migration script that represents these changes. It compares the current state of the models with the previous state and generates a script to make the database schema reflect these changes.
Step 4: Migrate your changes to your database by executing the command below
flask db upgrade
Flask db upgrade: After generating the migration script using flask db migrate, flask db upgrade is used to apply these changes to the database. It executes the migration script generated by flask db migrate, making the necessary alterations to the actual database schema.
Finally go to your Pg4Admin and you should now see your Category and Todo table in your database.
Thats all for this article, as always thanks for reading and if you have any questions or comment please leave them down below.
Todo Series Parts:
- Part 1: Building a User-Friendly Todo App with Flask - A Step-by-Step Guide for Setting up Flask Application template
- Part 2: Building a User-Friendly Todo App with Flask - A Step-by-Step Guide for setting up our models with foreign key relationships
- Part 3: Building a User-Friendly Todo App with Flask - A Step-by-Step Guide to Performing GET Operations and Rendering Data on HTML Pages
- Part 4: Building a User-Friendly Todo App with Flask - Step-by-Step Guide to Perform Form Submissions via POST Requests
- Part 5: Building a User-Friendly Todo App with Flask - Step-by-Step Guide to Update Todo and Category Items via PATCH Requests
- Part 6: Building a User-Friendly Todo App with Flask - Step-by-Step Guide to Delete Todo and Category Items via DELETE Requests