SQLAlchemy 2 In Practice - Chapter 4 - Many-To-Many Relationships
a day ago
- Many-to-many relationships require a join table to link two tables when foreign keys alone cannot represent the relationship.
- In SQLAlchemy, the join table is defined using the Table class from SQLAlchemy Core, with composite primary keys.
- Relationships use the 'secondary' argument to reference the join table, and both sides use back_populates to link.
- The relationship supports automatic insertion and deletion of join table entries via list operations like append and remove.
- Queries involving many-to-many relationships use automatic two-step joins (through the join table) and can be combined with other relationships.
- Deleting an entity automatically removes its links in the join table, and links can be detached using list removal methods.
- Alembic is introduced for database migrations, with setup involving env.py configuration and auto-generation of migration scripts.
- The import script is updated to use delete() instead of drop_all/create_all, and Alembic manages the database schema.