Sobes.tech
Junior — Middle

Can you explain the concept of composition in object-relational mappings (ORM)?

sobes.tech AI

Answer from AI

In ORM (Object-Relational Mapping), composition is a way of modeling relationships between objects where one object contains another as part of its structure.

For example, if you have User and Profile models, and the profile is part of the user, then User can contain a Profile object. In the database, this is usually reflected through foreign keys.

In Python ORM (such as SQLAlchemy or Django ORM), composition allows:

  • Embedding one object into another as an attribute.
  • Managing the lifecycle of the embedded object together with the parent.
  • Simplifying working with related data by accessing it through object properties.

Example in SQLAlchemy:

from sqlalchemy import Column, Integer, String, ForeignKey
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class Profile(Base):
    __tablename__ = 'profiles'
    id = Column(Integer, primary_key=True)
    bio = Column(String)
    user_id = Column(Integer, ForeignKey('users.id'))

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    profile = relationship('Profile', uselist=False, backref='user')

Here, User contains Profile through the relationship, which is an example of composition.