[파이썬] Peewee Model 상속

Peewee is a simple and lightweight ORM (Object-Relational Mapping) library for Python. It provides an easy-to-use API for interacting with databases in Python applications.

One of the key features of Peewee is its support for model inheritance. Model inheritance allows you to create a base model with shared fields and behaviors, and then define child models that inherit from the base model. This feature helps to reduce code duplication and promote code reusability in your database schema.

Defining a base model

To demonstrate Peewee model inheritance, let’s start by defining a base model called BaseModel that will contain common fields and methods shared among different models.

from peewee import Model, CharField, DateTimeField

class BaseModel(Model):
    name = CharField()
    created_at = DateTimeField()
    
    class Meta:
        database = <your_database_connection>

In the above code, BaseModel inherits from Model, which is the base class provided by Peewee for defining models. It contains two fields: name of type CharField and created_at of type DateTimeField.

Creating child models

Now, we can create child models that inherit from the BaseModel and add additional fields or override existing ones.

from peewee import TextField

class User(BaseModel):
    email = CharField(unique=True)
    password = CharField()

class Post(BaseModel):
    title = CharField()
    content = TextField()

In the above code, we have created two child models: User and Post. Both models inherit from the BaseModel and contain additional fields specific to their purpose.

Accessing fields and methods

When working with model inheritance, you can access the fields and methods defined in the base model from the child models.

user = User()
user.name = "John Doe"
user.email = "john@example.com"
user.password = "password123"
user.created_at = datetime.datetime.now()
user.save()

post = Post()
post.name = "My Post"
post.title = "Hello Peewee"
post.content = "This is a blog post created using Peewee."
post.created_at = datetime.datetime.now()
post.save()

In the above code, we create instances of the User and Post models and set the values for their respective fields. We can also access the methods inherited from the BaseModel like save() to save the objects in the database.

Conclusion

Using Peewee model inheritance, you can easily create a hierarchy of models in your Python applications. This helps to organize your code, reduce duplication, and improve code reusability. Peewee’s simple and intuitive API makes it a powerful tool for working with databases in Python.