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
course content

Зміст курсу

Professional Web API with Flask

Professional Web API with Flask

1. Introduction to the Course
2. Database and Models
3. Flask-Smorest and Schemas
4. Endpoints with Blueprints and MethodView
5. Authentication with JWT
6. Deployment

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:

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:

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

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?
In Flask-SQLAlchemy, how are many-to-many relationships typically implemented?

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

Виберіть правильну відповідь

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

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

Виберіть правильну відповідь

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 2. Розділ 5
We're sorry to hear that something went wrong. What happened?
some-alt