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!
š 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:
šÆ Let's create a simple example: A User (one) can have multiple Posts (many).
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.
šÆ Now, let's create an example where a User can follow multiple Blogs, and a Blog can have multiple Users following it.
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.
š 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.
First, let's create some sample data:
# 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()# 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.blogsWhat 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! š¤š