Зміст курсу
Professional Web API with Flask
Professional Web API with Flask
Many-to-One Relationship
To establish Many-to-One relationships between different tables in our database, we utilize an additional attribute called db.ForeignKey in our models. This attribute facilitates the creation of links between tables, enabling a hierarchical structure within the database. Let's delve into how this is achieved with practical examples.
Adding a Many-to-One Relationship in the Team Model
In the TeamModel, we introduce a club_id field, which serves as a foreign key to the clubs table:
club_id
is a database column that stores an integer value, designated as a foreign key (db.ForeignKey
), pointing to the id column of the clubs table. Settingnullable=False
ensures that every team record must be associated with a club, hence, this field cannot be empty.club
defines a relationship (db.relationship
) between theTeamModel
andClubModel
. By specifyingback_populates="teams"
in the ClubModel, it establishes a bidirectional link, allowing access from a club to all its associated teams and vice versa.
Establishing the Relationship in the Club Model
Similarly, in the club model, we define the relationship to teams as follows:
The lazy="dynamic" option is crucial for addressing the N+1 query problem, a common issue where a separate database query is executed for each of the N-related objects, plus an additional query for the primary object. This scenario can significantly degrade performance, especially with large datasets.
Many-to-One Relationship Between Players and Teams
The relationship between players and teams is also a Many-to-One type, meaning a team can have multiple players, but each player is associated with only one team. We add a db.ForeignKey
link in the player model to establish this:
And in the TeamModel, we define the relationship with players as:
This setup allows for a team to access all its players and each player to know which team they belong to, optimizing data retrieval and manipulation in applications that manage sports teams, clubs, and their members.
Дякуємо за ваш відгук!