Location>code7788 >text

Peewee: Python’s simple and powerful ORM framework

Popularity:440 ℃/2025-01-15 22:47:20

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

Introduced todayPeeweeAs a simple and powerfulORM(Object Relational Mapping) framework provides developers with an efficient and convenient way to interact with databases.

1. Peewee Overview

PeeweeIt is a simple and compactORM, its concept is simple and clear, easy to learn and use.

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

usedPythonEveryone knows,SQLAlchemyalmost alreadyPythonstandards inORMThe framework is powerful,

Why still usePeeweeWoolen cloth?

first,PeeweeThe design is more concise, its API is simple and intuitive, and the learning curve is gentle, so novices can get started quickly.SQLAlchemyRelatively complex and takes more time to master.

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

For example, in a small database application scenario,PeeweeAble to quickly build data operation modules.

Furthermore,PeeweeThe performance is excellent in specific scenarios, such asSQLiteDatabase operations occupy relatively low resources and can bring better operating results to applications.

In short, if the project is not large in scale or you are making some small tools, thenPeeweeIt will be more convenient.

2. Get started quickly

2.1. Initialize the database

There are corresponding initialization methods for different database types.

Next we choose to useSQLite

from peewee import SqliteDatabase

db = SqliteDatabase('my_database.db')

2.2. Model definition

existPeewee, create a model by defining a class, and the attributes of the class correspond to the 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 database and tables

Connect to the database and then useSqliteDatabaseto create the table.

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

After execution, you will find that the sqlite database and table are 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 you execute it repeatedly. 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, then callsaveMethod to 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. To get a single record:

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

 # Running results:
 # name: Harry, age: 23

2.5. Update records

Update the record, for example, change 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 easy:

().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, paging queries, etc.

3.1. Insert data in batches

In order to demonstrate the advanced query function, first insert a batch of data in batches.

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("Users who meet the conditions:")
 for u in users:
     print(f"{}: {}")

Running results:

$ .\
 Users who meet the conditions:
 Tom: 35
 kate: 42

The union of multiple conditions, such asid>4orage>20Data:

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

Running results:

$ .\
 Users who meet the conditions:
 harry: 23
 Tom: 35
 kate: 42

3.3. Sorting

Sorted by age:

users = ().order_by()

Running results:

$ .\
 Sorted by age:
 jerry: 12
 Lily: 20
 harry: 23
 Tom: 35
 kate: 42

Sort by decreasing age:

users = ().order_by(())

Running results:

$ .\
 Sort by decreasing age:
 kate: 42
 Tom: 35
 harry: 23
 Lily: 20
 jerry: 12

3.4. Paging query

Finally, let’s look at paginated queries, which are very useful when displaying large-scale data on the front end.

GeneralORMwill passSQLin the sentencelimitandoffsetTo implement paging query, andPeeweeDirectly provides paging query API.

page_number = 1 # Page serial number, starting from 1
 page_size = 3 #Amount of data per page

 users = ().paginate(page_number, page_size)
 print(f"Data on page {page_number}:")
 for u in users:
     print(f"{}: {}")

Running results:

$ .\
 Page 1 data:
 harry: 23
 Lily: 20
 Tom: 35

This displays the first 3 data. If the abovepage_numberg=2, then the remaining2 itemsdata.

4. Summary

PeeweeIt also has numerous extensions such asPlayhouseMore advanced features are provided, including specific extensions to different databases (e.g.SQLiteextension functions), model generation tools, database migration tools, reflection functions, etc., have been greatly enhanced.Peeweepracticality and flexibility.

This article introduces the most basic usage. Others include the establishment and query of relationships between multiple tables. Please refer to the official documentation.

In short,PeeweeWith its concise syntax, rich functions and good scalability, it has becomePythonA powerful tool for developers in database operations, whether it is a small project or a large application, it can provide efficient and reliable database interaction support.