[python] Peewee에서의 상속과 관계 정의하기

Peewee는 Python에서 작성된 간단하고 가벼운 ORM(Object-Relational Mapping) 라이브러리입니다. Peewee를 사용하면 데이터베이스와 객체 지향 모델 간의 상호 작용을 쉽게 할 수 있습니다. 이번에는 Peewee에서 상속과 관계를 어떻게 정의하는지에 대해 알아보겠습니다.

1. Inheritance(상속)

Peewee에서는 클래스 간의 상속을 통해 모델 간의 관계를 정의할 수 있습니다. 예를 들어, Person 모델이 User 모델을 상속받는다고 가정해보겠습니다.

from peewee import *

database = SqliteDatabase('my_database.db')

class Person(Model):
    name = CharField()
    age = IntegerField()

    class Meta:
        database = database

class User(Person):
    username = CharField(unique=True)
    password = CharField()

    class Meta:
        database = database

위의 예제에서 User 클래스가 Person 클래스를 상속받고 있습니다. User 모델은 Person 모델의 모든 필드와 메서드를 상속받게 됩니다. 따라서 User 객체를 통해 Person의 필드와 메서드에 접근할 수 있습니다.

2. Relationships(관계)

Peewee에서는 관계형 데이터베이스의 관계를 간단하게 정의할 수 있습니다. Peewee는 이를 위해 Foreign Key 또는 Many-to-Many 관계를 지원합니다.

Foreign Key(일대다 관계)

일대다 관계는 한 모델이 다른 모델을 참조하는 관계입니다. 예를 들어, Book 모델이 Author 모델을 참조한다고 가정해보겠습니다.

from peewee import *

database = SqliteDatabase('my_database.db')

class Author(Model):
    name = CharField()

    class Meta:
        database = database

class Book(Model):
    title = CharField()
    author = ForeignKeyField(Author)

    class Meta:
        database = database

위의 예제에서 Book 모델은 Author 모델을 참조하는 author 필드를 가지고 있습니다. 이를 통해 BookAuthor 사이에 일대다 관계가 생성됩니다.

Many-to-Many(다대다 관계)

다대다 관계는 한 모델이 다른 모델과 여러 개의 관계를 가지는 관계입니다. 예를 들어, Student 모델과 Course 모델이 다대다 관계에 있다고 가정해보겠습니다.

from peewee import *

database = SqliteDatabase('my_database.db')

class Student(Model):
    name = CharField()

    class Meta:
        database = database

class Course(Model):
    name = CharField()
    students = ManyToManyField(Student)

    class Meta:
        database = database

위의 예제에서 Course 모델은 Student 모델과 students 필드를 통해 다대다 관계를 가집니다. 이를 통해 CourseStudent 사이에 다대다 관계가 생성됩니다.

결론

Peewee를 사용하면 간단하고 직관적인 방법으로 상속과 관계를 정의할 수 있습니다. 위의 예제들을 참고하여 Peewee를 사용하면서 모델 간의 상속과 관계를 쉽게 정의해보세요.

참고 자료