SoFunction
Updated on 2025-03-10

Detailed explanation of the usage of Peewee, a simple and powerful ORM framework in Python

existPythonIn the development world, database operations are a crucial part.

What I introduced todayPeeweeAs a simple and powerfulORM(Object Relational Mapping) framework provides developers with efficient and convenient database interaction methods.

1. Peewee Overview

PeeweeIt's a simple and small oneORM, its concept is concise and clear, easy to learn and use.

Be able to work withSQLiteMySQLMariaDBPostgreSQLand other databases work together, with rich extension functions, and their source code is hosted onGitHub-peewee

UsedPythonEveryone knows,SQLAlchemyAlmost alreadyPythonThe standard inORMThe framework is powerful,

Why use itPeeweeWoolen cloth?

first,PeeweeThe design is simpler and intuitive, its API is smooth and learning curve, so novices can get started quickly, andSQLAlchemyRelatively complex and requires more time to master it.

Second,PeeweeThe amount of code is small. In some simple projects, its lightweight characteristics can make the project structure clearer and the development efficiency is higher.

For example, in small database application scenarios,PeeweeIt can quickly build a data operation module.

Furthermore,PeeweeThe performance of  excellent performance in specific scenarios, such asSQLiteThe database operation has relatively low resource usage, which can bring better operational results to the application.

In short, if the project is not large or you make some gadgets, thenPeeweeIt will be more handy.

2. Get started quickly

2.1. Initialize the database

For different database types, there are corresponding initialization methods.

Let's choose to useSQLite

from peewee import SqliteDatabase

db = SqliteDatabase('my_database.db')

2.2. Model definition

existPeeweeIn  , create a model by defining a class, and the properties of the class correspond to fields in the database table. For example:

from peewee import Model, CharField, IntegerField

class User(Model):
    class Meta:
        database = db

    username = CharField(unique=True)
    age = IntegerField()

2.3. Create databases and tables

Connect to the database and then you can use itSqliteDatabaseto create the table.

if __name__ == "__main__":
    ()
    db.create_tables([User])

After execution, you will find that the sqlite database and tables have been created.

$   .\my_database.db
SQLite version 3.45.3 2024-04-15 13:34:05 (UTF-16 console I/O)
Enter ".help" for usage hints.
sqlite> .tables
user

db.create_tablesIt doesn't matter if the table already exists, it will not be created repeatedly.

2.4. Data storage and retrieval

When storing data, first create a model instance and assign a value, and then callsaveMethods can save data to the database.

if __name__ == "__main__":
    user = User(username="Harry", age=23)
    ()

After running, query the database and find that the data has been written to the database.

sqlite> select * from user;
┌────┬──────────┬─────┐
│ id │ username │ age │
├────┼──────────┼─────┤
│ 1  │ Harry    │ 23  │
└────┴──────────┴─────┘

Various query methods can be used to retrieve data. For example, obtaining a single record:

user = ( == "Harry")
print(f"name: {}, age: {}")

# Run result:# name: Harry, age: 23

2.5. Update records

Update the record, such as changing the age above to 30.

(age=30).where( == 'Harry').execute()

After running:

sqlite> select * from user;
┌────┬──────────┬─────┐
│ id │ username │ age │
├────┼──────────┼─────┤
│ 1  │ Harry    │ 30  │
└────┴──────────┴─────┘

2.6. Delete records

Deleting records is also very simple:

().where( == 'Harry').execute()

After running:

sqlite> select * from user;
sqlite> select count(1) from user;
┌──────────┐
│ count(1) │
├──────────┤
│ 0        │
└──────────┘

3. Advanced query function

Advanced query functions include multi-condition filtering, sorting, and pagination query.

3.1. Batch insertion of data

To demonstrate the advanced query function, batch insert a batch of data first.

User.insert_many(users, fields=[, ]).execute()

Running results:

sqlite> select * from user;
┌────┬──────────┬─────┐
│ id │ username │ age │
├────┼──────────┼─────┤
│ 1  │ harry    │ 23  │
│ 2  │ lily     │ 20  │
│ 3  │ tom      │ 35  │
│ 4  │ jerry    │ 12  │
│ 5  │ kate     │ 42  │
└────┴──────────┴─────┘

3.2. Multi-condition query

The intersection of multiple conditions, such asid>2andage>30Data:

users = ().where(( > 2) & ( > 30)).execute()

print("Meet the user:")
for u in users:
    print(f"{}: {}")

Running results:

$   .\
Users who meet the criteria:
tom: 35
kate: 42

union of multiple conditions, e.g.id>4orage>20Data:

users = ().where(( > 4) | ( > 20)).execute()

Running results:

$   .\
Users who meet the criteria:
harry: 23
tom: 35
kate: 42

3.3. Sort

Sort by age:

users = ().order_by()

Running results:

$   .\
Sort by age:
jerry: 12
lily: 20
harry: 23
tom: 35
kate: 42

Sort by age reduction:

users = ().order_by(())

Running results:

$   .\
Sort by age reduction:
kate: 42
tom: 35
harry: 23
lily: 20
jerry: 12

3.4. Pagination query

Finally, let’s take a look at pagination queries, which are very useful when presenting large-scale data in the front-end.

GeneralORMWill passSQLIn the statementlimitandoffsetto implement pagination query, andPeeweeA paging query API is provided directly.

page_number = 1 # Page number, starting from 1page_size = 3  # The number of data per page
users = ().paginate(page_number, page_size)
print(f"The{page_number}Page data:")
for u in users:
    print(f"{}: {}")

Running results:

$   .\
Page 1 data:
harry: 23
lily: 20
tom: 35

This shows the first 3 data. If the abovepage_numberg=2, then the rest will be returned2 itemsdata.

4. Summary

PeeweeThere are also many expansions, such asPlayhouseProvides more advanced features, including specific extensions to different databases (e.g.SQLiteExtended functions), model generation tools, database migration tools, reflection functions, etc., greatly enhancePeeweePracticality and flexibility.

This article introduces the most basic usage method, and there are other aspects to establish and query relationships between multiple tables. Please refer to the official documentation.

Anyway,PeeweeWith its concise syntax, rich functions and good extensibility, it has becomePythonDevelopers’ powerful tools in database operations can provide efficient and reliable database interaction support, whether for small projects or large applications.

This is the end of this article about the detailed explanation of the usage of Peewee, the simple and powerful ORM framework of Python. For more related Python Peewee content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!