Learn Flask Β· 9/15

Advanced Databases: Managing Relationships

6 min read

Welcome back, intrepid coder! πŸš€

Having mastered the basics of databases in Flask, it's time to level up. In the real world, your data isn't a lonely island; it's an interconnected web of information. This guide will walk you through managing those connections, making your applications more powerful and efficient.

So, what's the big deal with relationships?

Imagine you're building a blog. You have users, and those users write posts. If you store users and posts in separate, unrelated tables, how do you know who wrote what? You'd have to resort to some clunky, inefficient methods. Database relationships solve this by creating explicit links between your tables. It's like giving your data a family tree.


πŸ§‘β€πŸ€β€πŸ§‘ One-to-Many Relationships (e.g., Users and Posts)

This is the most common type of relationship. Think of it like a parent and their children. One parent can have many children, but each child has only one biological mother. In our blog example, one user can write many posts, but each post is written by only one user.

Let's see it in action:

First, make sure you have Flask-SQLAlchemy installed:

bash
pip install Flask-SQLAlchemy

Now, let's define our models. We'll have a User model and a Post model.

python
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import os

basedir = os.path.abspath(os.path.dirname(__file__))
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'app.db')
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)
    # This is the "one" side of the relationship
    posts = db.relationship('Post', backref='author', lazy=True)

    def __repr__(self):
        return f'<User {self.username}>'

class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(120), nullable=False)
    content = db.Column(db.Text, nullable=False)
    # This is the "many" side. We need a foreign key to link to the User.
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)

    def __repr__(self):
        return f'<Post {self.title}>'

Breaking it down:

  • db.relationship('Post', backref='author', lazy=True): This is the magic part.
    • 'Post': Tells SQLAlchemy which model to connect to.
    • backref='author': This is a cool trick. It adds an author attribute to the Post model. So, if you have a post object, you can just do post.author to get the User who wrote it.
    • lazy=True: This means that when you load a user, SQLAlchemy won't fetch all their posts at once. It will only load them when you try to access the posts attribute. This is much more efficient, especially if a user has thousands of posts. You can also set it to 'dynamic' which returns a query object instead of a list, allowing you to further filter the results before loading them.
  • user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False): This is the crucial link.
    • db.ForeignKey('user.id'): This tells the Post model that the user_id column is linked to the id column of the user table. Note that we use the lowercase table name 'user'.

Creating and Querying:

Let's see how to use these related models.

python
with app.app_context():
    db.create_all()

    # Create a user
    user1 = User(username='Alice')
    db.session.add(user1)
    db.session.commit()

    # Create posts for that user
    post1 = Post(title='My First Post', content='Hello World!', author=user1)
    post2 = Post(title='Another Post', content='Flask is fun!', author=user1)
    db.session.add_all([post1, post2])
    db.session.commit()

    # Now, let's query
    alice = User.query.filter_by(username='Alice').first()
    print(f"Posts by {alice.username}:")
    for post in alice.posts:
        print(f"- {post.title}")

    # And the other way around, thanks to our backref!
    a_post = Post.query.first()
    print(f"The author of '{a_post.title}' is {a_post.author.username}")

πŸ”„ Many-to-Many Relationships (e.g., Posts and Tags)

Sometimes, the relationship is more complex. A single blog post can have multiple tags (e.g., 'python', 'flask', 'webdev'), and a single tag can be applied to many posts. This is a many-to-many relationship.

To handle this, we need a third table, often called an association table. Its only job is to link the other two tables together.

Let's build it:

We'll add a Tag model and an association table to our existing setup.

python
# This is our association table
post_tags = db.Table('post_tags',
    db.Column('post_id', db.Integer, db.ForeignKey('post.id'), primary_key=True),
    db.Column('tag_id', db.Integer, db.ForeignKey('tag.id'), primary_key=True)
)

class Post(db.Model):
    # ... (previous columns)
    tags = db.relationship('Tag', secondary=post_tags, lazy='subquery',
        backref=db.backref('posts', lazy=True))

class Tag(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50), unique=True, nullable=False)

    def __repr__(self):
        return f'<Tag {self.name}>'

What's new?

  • post_tags = db.Table(...): We define the association table directly. It doesn't need its own model class because it's just holding foreign keys.
  • secondary=post_tags: In the db.relationship on the Post model, we tell SQLAlchemy to use our post_tags table to manage this relationship.
  • backref=db.backref('posts', lazy=True): Just like before, this adds a posts attribute to our Tag model, so we can easily see all the posts associated with a given tag.

Adding and Querying:

python
with app.app_context():
    db.create_all()

    # Create some tags
    tag1 = Tag(name='python')
    tag2 = Tag(name='flask')
    tag3 = Tag(name='webdev')
    db.session.add_all([tag1, tag2, tag3])
    db.session.commit()

    # Get a post and add tags to it
    a_post = Post.query.first()
    a_post.tags.append(tag1)
    a_post.tags.append(tag2)
    db.session.commit()

    # Querying posts by tag
    python_tag = Tag.query.filter_by(name='python').first()
    print(f"Posts tagged with '{python_tag.name}':")
    for post in python_tag.posts:
        print(f"- {post.title}")

⚑ Joins and Efficient Querying Techniques

When you access related data like user.posts, SQLAlchemy is often doing a separate query behind the scenes. For a few objects, this is fine. But if you're loading a list of 100 posts and then need the author for each one, that's 101 separate queries! 😱 This is known as the "N+1 problem" and it can bring your application to a crawl.

The solution is to use joins. A join allows you to fetch data from multiple tables in a single query.

How to Join:

SQLAlchemy is smart and often does implicit joins for you, but it's good to know how to do it explicitly for more complex scenarios.

python
from sqlalchemy.orm import joinedload

with app.app_context():
    # Inefficient way (can lead to N+1 problem)
    posts = Post.query.all()
    for post in posts:
        # This will trigger a separate query for each post's author
        print(f"Title: {post.title}, Author: {post.author.username}")

    print("\n--- Using a join ---")

    # Efficient way using joinedload
    posts_with_authors = Post.query.options(joinedload(Post.author)).all()
    for post in posts_with_authors:
        # No extra query here! The author was loaded with the post.
        print(f"Title: {post.title}, Author: {post.author.username}")

    # Another way to join for filtering
    # Get all posts by a user named 'Alice'
    posts_by_alice = Post.query.join(User).filter(User.username == 'Alice').all()
    print(f"\nPosts by Alice (found via join): {posts_by_alice}")

Key Takeaways on Joins:

  • joinedload(): This is your best friend for avoiding the N+1 problem when you know you'll need the related objects.
  • query.join(): Use this when you want to filter based on a related model's attributes.
  • SQLAlchemy's "Auto-Join" or "Implicit Join" feature simplifies many queries by automatically generating the necessary SQL JOIN statements when you work with related models.

πŸ“š Further Reading:

Challenge

You are building the database backend for an online learning platform. Your task is to model the relationships between instructors, courses, and students using Flask-SQLAlchemy.

Requirements:

  1. Define an Association Table named enrollments to manage the many-to-many relationship between students and courses. It must contain foreign keys to the student and course tables.

  2. Define the Instructor Model:

    • It must have an id (integer, primary key) and a name (string, not nullable).
    • Establish a one-to-many relationship with the Course model. The collection on the Instructor instance should be named courses, and the back-reference on a Course instance should be instructor.
  3. Define the Course Model:

    • It must have an id (integer, primary key) and a title (string, not nullable).
    • It must contain a foreign key column named instructor_id that links to the instructor.id and cannot be null.
    • Establish a many-to-many relationship with the Student model using the enrollments association table. The back-reference on a Student instance should be named courses.
  4. Define the Student Model:

    • It must have an id (integer, primary key) and a username (string, unique, not nullable).

Complete the code in the editor to correctly define these models and their relationships.

Expected result

Your solution should correctly implement the database models and relationships as described.

enrollments table:

  • Defined using db.Table.
  • Contains two columns, one for student_id and one for course_id.
  • Each column is an Integer and a db.ForeignKey pointing to student.id and course.id respectively.

Instructor Model:

  • id: An Integer column set as the primary key.
  • name: A non-nullable String column.
  • courses: A db.relationship defined to link to the Course model, with backref='instructor' and lazy=True.

Course Model:

  • id: An Integer column set as the primary key.
  • title: A non-nullable String column.
  • instructor_id: An Integer column with a db.ForeignKey('instructor.id') and set to nullable=False.
  • students: A db.relationship defined to link to the Student model. It must specify the enrollments table in the secondary parameter and have a backref named courses.

Student Model:

  • id: An Integer column set as the primary key.
  • username: A unique and non-nullable String column.
python

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.