existPython
In the development world of , database operations are a crucial part.
Introduced todayPeewee
As a simple and powerfulORM
(Object Relational Mapping) framework provides developers with an efficient and convenient way to interact with databases.
1. Peewee Overview
Peewee
It is a simple and compactORM
, its concept is simple and clear, easy to learn and use.
able to work withSQLite
、MySQL
、MariaDB
、PostgreSQL
and other databases work together, with rich extension functions, and its source code is hosted onGitHub-peewee。
usedPython
Everyone knows,SQLAlchemy
almost alreadyPython
standards inORM
The framework is powerful,
Why still usePeewee
Woolen cloth?
first,Peewee
The design is more concise, its API is simple and intuitive, and the learning curve is gentle, so novices can get started quickly.SQLAlchemy
Relatively complex and takes more time to master.
Secondly,Peewee
The 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,Peewee
Able to quickly build data operation modules.
Furthermore,Peewee
The performance is excellent in specific scenarios, such asSQLite
Database 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, thenPeewee
It 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 useSqliteDatabase
to 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_tables
It 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 callsave
Method 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>2
andage>30
Data:
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>4
orage>20
Data:
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.
GeneralORM
will passSQL
in the sentencelimit
andoffset
To implement paging query, andPeewee
Directly 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
Peewee
It also has numerous extensions such asPlayhouse
More advanced features are provided, including specific extensions to different databases (e.g.SQLite
extension functions), model generation tools, database migration tools, reflection functions, etc., have been greatly enhanced.Peewee
practicality 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,Peewee
With its concise syntax, rich functions and good scalability, it has becomePython
A 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.