peewee优雅的ORM框架-入门

2022-06-17 08:39:28 浏览数 (1)

前言

PythonORM 框架中,比较主流的有 Sqlalchemypeeweepony 等等。但是其中 peeweeDjangoModels 框架很像,如果了解 Django 的同学肯定对 peewee 会很亲切。今天我们就一起走进 peewee 的世界。

peewee 的世界

安装

代码语言:javascript复制
pip install peewee

创建数据库&表

代码语言:javascript复制
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

代码语言:javascript复制
# 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

代码语言:javascript复制
# 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

代码语言:javascript复制
# 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

代码语言:javascript复制
# delete info
res = people.select().where(people.name == 'phyger1').get()
res.delete_instance()
res.save()

更多内容详见官方文档:

代码语言:javascript复制
http://docs.peewee-orm.com/en/latest/peewee/quickstart.html

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

0 人点赞