Sobes.tech
Junior — Middle

How to implement a many-to-many relationship in SQLAlchemy 2.0?

sobes.tech AI

Answer from AI

In SQLAlchemy 2.0, a many-to-many relationship is implemented through an association table that contains foreign keys to both related tables. Then, in the models, the relationship parameter is used with this table.

Example:

from sqlalchemy import Table, Column, Integer, ForeignKey
from sqlalchemy.orm import relationship, declarative_base

Base = declarative_base()

association_table = Table(
    'association', Base.metadata,
    Column('left_id', ForeignKey('left.id'), primary_key=True),
    Column('right_id', ForeignKey('right.id'), primary_key=True)
)

class Left(Base):
    __tablename__ = 'left'
    id = Column(Integer, primary_key=True)
    rights = relationship("Right", secondary=association_table, back_populates="lefts")

class Right(Base):
    __tablename__ = 'right'
    id = Column(Integer, primary_key=True)
    lefts = relationship("Left", secondary=association_table, back_populates="rights")

This approach allows for convenient working with multiple relationships between objects.