[파이썬] Peewee Primary Key 설정

When working with databases in Python, Peewee is a lightweight and expressive ORM (Object Relational Mapper) that simplifies database interactions. One of the key aspects of defining a database table is the configuration of the primary key. In this blog post, we will explore how to set up a primary key in Peewee using Python.

What is a Primary Key?

A primary key is a column or set of columns in a database table that uniquely identifies each row. It ensures the integrity and consistency of the data by enforcing uniqueness and providing a reliable way to reference a specific row in a table. Usually, a primary key is an auto-incrementing integer field, but it can also be a combination of multiple fields or even a UUID.

Setting up a Primary Key in Peewee

To define a primary key in Peewee, we can make use of the PrimaryKeyField class provided by the library. Let’s take a look at a simple example where we create a User table with an auto-incrementing integer primary key.

from peewee import *

# Create a database object
database = SqliteDatabase('my_database.db')

# Define a model class
class User(Model):
    id = PrimaryKeyField()
    username = CharField()
    email = CharField()

    class Meta:
        database = database

# Connect to the database
database.connect()

# Create the table
database.create_tables([User])

# Insert a new user
new_user = User.create(username='john', email='john@example.com')

# Get a user by their primary key value
user = User.get(User.id == 1)

# Update a user's details
user.username = 'jane'
user.save()

# Delete a user
user.delete_instance()

In the above example, we define the id field as a PrimaryKeyField. This will automatically configure the field to be the primary key for the User table. We can then perform CRUD (Create, Read, Update, Delete) operations using this primary key.

Additional Primary Key configurations

Peewee provides various additional options to configure the primary key field based on our specific requirements. Some of the commonly used options are:

The above options can be added to the PrimaryKeyField definition in the model class based on the desired configuration.

Conclusion

Setting up a primary key in Peewee is a straightforward process. By utilizing the PrimaryKeyField class, we can define the primary key for our database table. Peewee offers flexibility and various configuration options to suit different primary key requirements. With Peewee’s simplicity and power, working with databases in Python becomes an enjoyable experience.