Flask Tutorials: Relationships (One-to-Many, Many-to-Many)

beginner
22 min

Flask Tutorials: Relationships (One-to-Many, Many-to-Many)

Welcome back to CodeYourCraft! Today, we're diving deep into the world of relationships in Flask. Relationships are crucial when you're building complex applications and handling multiple data entities. Let's get started!

Understanding Relationships

šŸ“ Note: In a database, relationships are connections between tables that help us relate one table's data to another table's data.

In Flask, we can create relationships using SQLAlchemy, an Object Relational Mapping (ORM) tool. Here are two common types of relationships:

  1. One-to-Many (1:N): One record in one table can be associated with multiple records in another table.
  2. Many-to-Many (N:M): Multiple records in one table can be associated with multiple records in another table, and vice versa.

One-to-Many (1:N) Relationship

šŸŽÆ Let's create a simple example: A User (one) can have multiple Posts (many).

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) posts = db.Relationship('Post', backref='author', lazy=True) class Post(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(100), nullable=False) content = db.Column(db.Text, nullable=False) user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)

šŸ’” Pro Tip: The lazy=True parameter in the User's posts relationship means that when you access the posts attribute of a User object, it won't immediately load the associated Post objects. Instead, it will load them on demand.

Many-to-Many (N:M) Relationship

šŸŽÆ Now, let's create an example where a User can follow multiple Blogs, and a Blog can have multiple Users following it.

python
from flask_sqlalchemy import SQLAlchemy from sqlalchemy.orm import relationship db = SQLAlchemy() association_table = db.Table('user_blog', db.Column('user_id', db.Integer, db.ForeignKey('user.id')), db.Column('blog_id', db.Integer, db.ForeignKey('blog.id'))) class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True, nullable=False) blogs = relationship('Blog', secondary=association_table, backref=db.backref('followers', lazy=True)) class Blog(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(100), nullable=False) users = relationship('User', secondary=association_table)

šŸ’” Pro Tip: The association_table is a join table that holds the relationship between User and Blog.

Creating, Reading, Updating, and Deleting (CRUD)

šŸ“ Note: We'll need to implement CRUD operations to work with our data.

For the sake of brevity, let's only focus on creating and querying. We'll leave updating and deleting for you to explore as an exercise.

Creating Data

First, let's create some sample data:

python
# Create a new user new_user = User(username='test_user') db.session.add(new_user) db.session.commit() # Create a new blog new_blog = Blog(title='Test Blog') db.session.add(new_blog) db.session.commit() # Associate the user with the blog new_user.blogs.append(new_blog) db.session.commit()

Querying Data

python
# Get the user user = User.query.filter_by(username='test_user').first() # Get the blog blog = Blog.query.filter_by(title='Test Blog').first() # Get the user's blogs blogs = user.blogs

Quiz

Quick Quiz
Question 1 of 1

What is the purpose of the `association_table` in a Many-to-Many relationship?

And there you have it! Relationships in Flask can seem a bit complex at first, but with practice, they'll become second nature. Happy coding! šŸ¤–šŸš€