前言
在 Python
的 ORM
框架中,比较主流的有 Sqlalchemy
,peewee
,pony
等等。但是其中 peewee
和 Django
的 Models
框架很像,如果了解 Django
的同学肯定对 peewee
会很亲切。今天我们就一起走进 peewee
的世界。
peewee 的世界
安装
pip install peewee
创建数据库&表
from peewee import *
from datetime import date
from playhouse.migrate import *
# 如果db不存在,会自动创建
db = SqliteDatabase('pp.db')
class people(Model):
# 默认会有ID作为主键自增
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()
查看数据库
在当前路径下查看是否创建了 pp.db
,是否在数据库中创建了 people
表。
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()
CRUD-R
# search people
res = people.get_by_id(1)
print('ID为1的数据的name是:',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('name为phyger2的ID是:',rep.id)
rea = people.select().where(people.people_status == True)
for i in rea:
print(i.name)
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)
CRUD-D
# delete info
res = people.select().where(people.name == 'phyger1').get()
res.delete_instance()
res.save()
更多内容详见官方文档:
http://docs.peewee-orm.com/en/latest/peewee/quickstart.html
以上就是今天的全部内容了,感谢您的阅读,我们下节再会。
评论区