Зміст курсу
Professional Web API with Flask
Professional Web API with Flask
Many-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.
Дякуємо за ваш відгук!