Sobes.tech
Junior — Middle

Explain the principle of declarative definition of relationships and tables in SQLAlchemy.

sobes.tech AI

Answer from AI

The declarative style in SQLAlchemy allows you to define tables and relationships between them using Python classes that inherit from the base class declarative_base(). Each class corresponds to a table in the database, and the class attributes are the columns of the table.

Relationships between tables are defined through special properties, such as relationship(), which establish links between class objects, as well as through foreign keys (ForeignKey). This enables working with the database at the object level, and SQLAlchemy automatically generates the necessary SQL queries.

Example:

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

Base = declarative_base()

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    addresses = relationship('Address', back_populates='user')

class Address(Base):
    __tablename__ = 'addresses'
    id = Column(Integer, primary_key=True)
    email = Column(String)
    user_id = Column(Integer, ForeignKey('users.id'))
    user = relationship('User', back_populates='addresses')

Here, User and Address are tables, and relationship establishes a bidirectional link between them.