Junior — Middle
What is the role of the relationship parameter in the ORM library SQLAlchemy and why is it used?
sobes.tech AI
Answer from AI
The relationship parameter in SQLAlchemy is used to define the relationship between two models (tables) in object-relational mapping (ORM). It describes how objects of one model are related to objects of another, such as one-to-one, one-to-many, or many-to-many.
Purpose of relationship:
- Allows convenient access to related objects via Python attributes without writing SQL queries.
- Automatically manages loading related data (lazy loading, eager loading).
- Provides cascade operations (e.g., deleting related objects).
Example:
from sqlalchemy import Column, Integer, String, ForeignKey
from sqlalchemy.orm import relationship
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
posts = relationship('Post', back_populates='author')
class Post(Base):
__tablename__ = 'posts'
id = Column(Integer, primary_key=True)
title = Column(String)
author_id = Column(Integer, ForeignKey('users.id'))
author = relationship('User', back_populates='posts')
Here, posts in the user is a list of related posts, and author in the post is its author.