[파이썬] Peewee shell 활용

Peewee is a simple yet powerful Object-Relational Mapping (ORM) library for Python. It provides a convenient way to interact with relational databases using Python code. In this blog post, we will explore how to leverage the Peewee shell to interactively interact with your database.

Introduction to Peewee shell

The Peewee shell is a command-line tool that allows you to connect to your database and perform various database operations using Peewee syntax. It provides an interactive environment where you can explore your database schema, query data, and even perform database migrations.

Installing Peewee shell

To start using the Peewee shell, you need to install the Peewee library first. You can use the following command to install it:

pip install peewee

Connecting to the database

Once you have installed Peewee, you can start the Peewee shell by running the pwiz.py script followed by the database connection details. Here’s an example:

python pwiz.py -e sqlite:///mydatabase.db

In the above example, we are connecting to a SQLite database named mydatabase.db.

Exploring the database schema

After connecting to the database, you can use various shell commands to explore the database schema. Here are some common commands:

Querying data

The Peewee shell provides a convenient way to query data from your database. You can write Peewee queries directly in the shell and get the results instantly. Here’s an example:

# Import the necessary models from your project
from models import User

# Query all the users from the User table
users = User.select()

# Iterate over the results and print the usernames
for user in users:
    print(user.username)

In the above example, we are querying all the users from the User table and printing their usernames.

Performing database migrations

The Peewee shell also supports the migration of database schema changes. You can generate migration scripts for schema changes, apply them to the database, and even rollback changes if needed. Here’s an example:

# Generate a migration script for schema changes
python pwiz.py -e sqlite:///mydatabase.db --auto

# Apply the generated migration script
python manage.py migrate

# Rollback the last migration
python manage.py rollback

In the above example, we are generating a migration script for any schema changes and applying it to the database using the migrate command. We can also rollback the last migration using the rollback command if needed.

Conclusion

The Peewee shell is a powerful tool that allows you to interactively work with your database using Peewee syntax. It provides a convenient way to explore the database schema, query data, and perform database migrations. By leveraging the Peewee shell, you can streamline your database operations and focus more on your application logic.