Flask Relationships [IN PROGRESS] - MantsSk/CA_PTUA14 GitHub Wiki

Introduction to Relationships in Flask SQLAlchemy

In Flask SQLAlchemy, relationships define how different database tables are related to each other. These relationships can be one-to-one, one-to-many, or many-to-many. By defining relationships between tables, you can efficiently query and manipulate related data.

Types of Relationships

One-to-One Relationship: In a one-to-one relationship, one record in a table is associated with one and only one record in another table.

One-to-Many Relationship: In a one-to-many relationship, one record in a table can be associated with one or more records in another table.

Many-to-Many Relationship: A many-to-many relationship occurs when multiple records in a table are associated with multiple records in another table.

Defining Relationships in Flask SQLAlchemy

To define relationships between tables in Flask SQLAlchemy, you use the relationship() function. This function is used within model classes to specify how different tables are related.

Here's an example of how to define different types of relationships:

from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

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

class Child(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    parent_id = db.Column(db.Integer, db.ForeignKey('parent.id'), nullable=False)

One-to-Many Relationship: In the Parent class, the children attribute is defined using relationship(). This establishes a one-to-many relationship between Parent and Child models. The backref parameter specifies the name of the attribute that will be added to the Child model to access its parent.

Many-to-One Relationship: In the Child class, the parent_id column is defined as a foreign key referencing the id column of the Parent model. This establishes a many-to-one relationship between Child and Parent models.

Using Relationships in Queries

Once relationships are defined, you can use them to perform queries that involve related data. For example:

# Get all children of a parent
parent = Parent.query.get(parent_id)
children = parent.children

# Get the parent of a child
child = Child.query.get(child_id)
parent = child.parent

Consider a simple blogging platform with three main entities: User, Post, and Comment.