目 录CONTENT

文章目录

peewee优雅的ORM框架-入门

phyger
2022-03-26 / 0 评论 / 1 点赞 / 1,350 阅读 / 1,433 字 / 正在检测是否收录...

前言

PythonORM 框架中,比较主流的有 Sqlalchemypeeweepony 等等。但是其中 peeweeDjangoModels 框架很像,如果了解 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 表。

创建的db

数据库&表在SQLitebrowser中

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)

修改后的结果

SQLitebrowser中的结果

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

以上就是今天的全部内容了,感谢您的阅读,我们下节再会。

1

评论区