0
0
Flaskframework~5 mins

Relationships (one-to-many) in Flask

Choose your learning style9 modes available
Introduction

A one-to-many relationship connects one item to many others. It helps organize related data clearly.

You want to link a blog author to many blog posts.
You need to connect a customer to multiple orders.
You want to store a category with many products.
You want to track a teacher with many students.
Syntax
Flask
class Parent(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    children = db.relationship('Child', back_populates='parent')

class Child(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    parent_id = db.Column(db.Integer, db.ForeignKey('parent.id'))
    parent = db.relationship('Parent', back_populates='children')

db.relationship defines the link from one side to many.

db.ForeignKey sets the connection on the many side.

Examples
Author has many posts. Each post links back to one author.
Flask
class Author(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    posts = db.relationship('Post', back_populates='author')

class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    author_id = db.Column(db.Integer, db.ForeignKey('author.id'))
    author = db.relationship('Author', back_populates='posts')
Category holds many products. Each product belongs to one category.
Flask
class Category(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    products = db.relationship('Product', back_populates='category')

class Product(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    category_id = db.Column(db.Integer, db.ForeignKey('category.id'))
    category = db.relationship('Category', back_populates='products')
Sample Program

This example creates an author and two posts linked to that author. It then prints the author's name and the titles of their posts.

Flask
from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)

class Author(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50))
    posts = db.relationship('Post', back_populates='author')

class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100))
    author_id = db.Column(db.Integer, db.ForeignKey('author.id'))
    author = db.relationship('Author', back_populates='posts')

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

    # Create an author
    author = Author(name='Alice')
    db.session.add(author)
    db.session.commit()

    # Create posts linked to author
    post1 = Post(title='First Post', author=author)
    post2 = Post(title='Second Post', author=author)
    db.session.add_all([post1, post2])
    db.session.commit()

    # Print author and their posts
    print(f"Author: {author.name}")
    for post in author.posts:
        print(f"- Post: {post.title}")
OutputSuccess
Important Notes

Always define db.relationship on the 'one' side and db.ForeignKey on the 'many' side.

Use back_populates to keep both sides connected and easy to access.

Remember to create and commit your database session to save changes.

Summary

One-to-many links one item to many related items.

Use db.relationship and db.ForeignKey together.

This helps organize and access related data easily.