Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

preface

Among Python ORM frameworks, the mainstream ones are Sqlalchemy, PeeWee, Pony, and so on. But PeeWee is very similar to Djangos Models framework, and those of you who know Django will be very familiar with PeeWee. Today we are going into peewee’s world.

Peewee world

The installation

pip install peewee
Copy the code

Create databases & tables

from peewee import *
from datetime import date
from playhouse.migrate import *

If the db does not exist, it will be created automatically
db = SqliteDatabase('pp.db')

class people(Model) :
    # default ID as primary key increment
    name = CharField()
    birth = DateField()
    people_status = BooleanField(default=True)
    class Meta:
        database = db

# connect db
db.connect()

# create table
db.create_tables([
    people,
])

# close db
db.close()
Copy the code

Viewing a Database

Check whether pp.db is created in the current path and whether the people table is created in the database.

CURD-C

# add people
phyger = people(name='phyger1',birth=date(1990.1.1))
phyger.save()

# Too
pp = people.create(name='phyger2',birth=date(1991.1.2))
pp.save()
Copy the code

CRUD-R

# search people
res = people.get_by_id(1)
print('The name of the data with ID 1 is:',res.name)


# search all (list)
ret = people.select()
for i in ret:
    print(i.id, i.name)

# where

rep = people.select().where(people.name == 'phyger2').get()
print('ID of phyger2 whose name is:',rep.id)

rea = people.select().where(people.people_status == True)
for i in rea:
    print(i.name)
Copy the code

CRUD-U

# update info
rep = people.select().where(people.name == 'phyger2').get()

# modify status
rep.people_status=False
# don't forget save
rep.save()
# search phyger2's status
res = people.select().where(people.name == 'phyger2').get()
print("phyger2's status is : ",res.people_status)
Copy the code

CRUD-D

# delete info
res = people.select().where(people.name == 'phyger1').get()
res.delete_instance()
res.save()
Copy the code

See the official documentation for more details:

http://docs.peewee-orm.com/en/latest/peewee/quickstart.html
Copy the code

That’s all for today, thank you for reading, and we’ll see you next time.