Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ Many-to-Many Relationship | Database and Models
/
Professional Web API with Flask

bookMany-to-Many Relationship

メニューを表示するにはスワイプしてください

In database design, many-to-many relationships are common, such as between teams and managers, where a team can have multiple managers and a manager can handle multiple teams. SQLAlchemy handles these relationships using an associative table that stores foreign keys referencing the primary keys of the related models.

Creating an Associative Table in the Models Package

To establish a many-to-many relationship, typically, an associative table is utilized. This table contains Foreign Keys from both related models. Here's how this can be implemented in your application:

First, within the models package, create a new file named teams_managers.py. In this file, we will initialize a new associative table:

from db import db

class TeamsManagers(db.Model):
    __tablename__ = "teams_managers"

    id = db.Column(db.Integer, primary_key=True)
    team_id = db.Column(db.Integer, db.ForeignKey("teams.id"))
    manager_id = db.Column(db.Integer, db.ForeignKey("users.id"))

This table, teams_managers, acts as the bridge between the TeamModel and UserModel (assuming users act as managers in this context), storing relationships between teams and their managers.

Defining Relationships in Models

Next, we return to the files where our models are defined. In the TeamModel, specify a relationship to the UserModel for managers and use the secondary argument to link to the new associative table:

managers = db.relationship("UserModel", back_populates="teams", secondary="teams_managers")

Repeat the process for the UserModel, establishing a relationship to the TeamModel for teams field:

teams = db.relationship("TeamModel", back_populates="managers", secondary="teams_managers")

By defining these relationships, SQLAlchemy understands how to query and join these tables, allowing for efficient data retrieval and manipulation across many-to-many relationships.

Note

It's important to note that simply defining these relationships and associative table does not automatically update your database schema. To apply these changes to the database, a process known as migration is necessary, which we will explore in the next chapter.

1. In Flask-SQLAlchemy, how are many-to-many relationships typically implemented?

2. Which statement best describes the secondary parameter in the db.relationship() function?

question mark

In Flask-SQLAlchemy, how are many-to-many relationships typically implemented?

正しい答えを選んでください

question mark

Which statement best describes the secondary parameter in the db.relationship() function?

正しい答えを選んでください

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 2.  5

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 2.  5
some-alt