In this blog post, we will explore how to define models using Peewee, a lightweight and expressive Object-Relational Mapping (ORM) library for Python.
What is Peewee?
Peewee is a simple, yet powerful ORM that makes it easy to interact with databases using Python. It provides a high-level API to define database tables as Python classes and perform common database operations such as creating, querying, updating, and deleting records.
Installation
To get started, you need to install Peewee. You can use pip, the Python package installer, to install Peewee by executing the following command:
pip install peewee
Define a Model
To define a model in Peewee, you need to create a class that inherits from the peewee.Model base class. This class will represent a table in your database.
Let’s consider an example of a User model with id, username, and email fields. Here’s how you can define this model:
from peewee import *
db = SqliteDatabase('users.db') # Connect to a SQLite database
class User(Model):
id = AutoField()
username = CharField(unique=True)
email = CharField()
class Meta:
database = db
In the above example:
- We import the necessary classes from the
peeweemodule. - We create an instance of the
SqliteDatabaseclass to specify the database connection. - We define a
Userclass that inherits from theModelclass. - Inside the
Userclass, we define the fields of the table as class variables. - We use various field types such as
AutoFieldfor the primary key,CharFieldfor username and email, etc. - We also define a nested
Metaclass to specify the database connection for the model.
Performing Database Operations
Once we have defined the User model, we can perform various database operations such as creating, querying, updating, and deleting records.
Here are some examples:
Creating a record:
user = User(username='john_doe', email='john.doe@example.com')
user.save()
Querying records:
users = User.select()
for user in users:
print(user.username, user.email)
Updating a record:
user = User.get(User.username == 'john_doe')
user.email = 'john_doe@example.com'
user.save()
Deleting a record:
user = User.get(User.username == 'john_doe')
user.delete_instance()
Conclusion
In this blog post, we have learned how to define models using Peewee, a powerful and lightweight ORM library for Python. We have seen how to create a model class, perform database operations, and use field types provided by Peewee. Peewee makes it easy and efficient to work with databases in Python, allowing you to focus on building your application logic.
If you are interested in learning more about Peewee, I recommend checking out the official documentation for detailed information and advanced usage: Peewee Documentation