[python] SQLAlchemy의 데이터베이스 관계 설정

SQLAlchemy는 파이썬에서 데이터베이스를 조작하기 위한 강력한 ORM(Object-Relational Mapping) 라이브러리입니다. SQLAlchemy를 사용하면 데이터베이스 테이블 간의 관계를 쉽게 설정할 수 있습니다. 이번 글에서는 SQLAlchemy를 사용하여 데이터베이스 관계를 설정하는 방법에 대해 알아보겠습니다.

1. One-to-One 관계 설정

One-to-One 관계는 한 테이블의 레코드가 다른 테이블의 레코드와 하나씩 대응하는 관계를 의미합니다. SQLAlchemy에서는 relationship 함수를 사용하여 One-to-One 관계를 설정할 수 있습니다. 예를 들어, User 테이블과 Profile 테이블이 있을 때, User 테이블의 각 레코드는 Profile 테이블의 한 레코드와 대응될 수 있습니다.

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

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    username = Column(String)

    profile = relationship("Profile", uselist=False, back_populates="user")

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

    user = relationship("User", back_populates="profile")

위의 예제에서 User 클래스의 profile 변수는 relationship 함수를 사용하여 Profile 클래스와의 관계를 설정하였습니다. uselist=False 옵션을 주어 One-to-One 관계임을 나타내고, back_populates 옵션을 사용하여 양방향 관계를 설정하였습니다.

2. One-to-Many 관계 설정

One-to-Many 관계는 한 테이블의 레코드가 다른 테이블의 레코드 여러 개와 대응하는 관계를 의미합니다. SQLAlchemy에서는 relationship 함수를 사용하여 One-to-Many 관계를 설정할 수 있습니다. 예를 들어, Author 테이블과 Book 테이블이 있을 때, 한 명의 작가는 여러 권의 책을 작성할 수 있습니다.

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

class Author(Base):
    __tablename__ = 'authors'
    id = Column(Integer, primary_key=True)
    name = Column(String)

    books = relationship("Book", back_populates="author")

class Book(Base):
    __tablename__ = 'books'
    id = Column(Integer, primary_key=True)
    title = Column(String)
    author_id = Column(Integer, ForeignKey('authors.id'))

    author = relationship("Author", back_populates="books")

위의 예제에서 Author 클래스의 books 변수는 relationship 함수를 사용하여 Book 클래스와의 관계를 설정하였습니다. back_populates 옵션을 사용하여 양방향 관계를 설정하였습니다.

3. Many-to-Many 관계 설정

Many-to-Many 관계는 한 테이블의 레코드가 다른 테이블의 레코드 여러 개와, 그 반대로 다른 테이블의 레코드 하나가 한 테이블의 레코드 여러 개와 대응하는 관계를 의미합니다. SQLAlchemy에서는 relationship 함수를 사용하여 Many-to-Many 관계를 설정할 수 있습니다. 예를 들어, Student 테이블과 Course 테이블이 있을 때, 한 명의 학생은 여러 과목을 수강할 수 있고, 한 과목은 여러 학생에게 수강될 수 있습니다.

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

association_table = Table('association', Base.metadata,
    Column('student_id', Integer, ForeignKey('students.id')),
    Column('course_id', Integer, ForeignKey('courses.id'))
)

class Student(Base):
    __tablename__ = 'students'
    id = Column(Integer, primary_key=True)
    name = Column(String)

    courses = relationship("Course", secondary=association_table, back_populates="students")

class Course(Base):
    __tablename__ = 'courses'
    id = Column(Integer, primary_key=True)
    name = Column(String)

    students = relationship("Student", secondary=association_table, back_populates="courses")

위의 예제에서 Student 클래스와 Course 클래스는 association_table 테이블을 통해 Many-to-Many 관계를 설정하였습니다. secondary 옵션을 사용하여 관계를 맺는 테이블을 지정하였으며, back_populates 옵션을 사용하여 양방향 관계를 설정하였습니다.

이처럼 SQLAlchemy를 사용하면 간단하게 데이터베이스 테이블 간의 관계를 설정할 수 있습니다. SQLAlchemy의 자세한 사용법은 공식 문서를 참고하세요.