peewee优雅的ORM框架-入门-peewee-1

前言

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

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

版权声明:除特殊说明,博客文章均为phyger原创,依据CC BY-SA 4.0许可证进行授权,转载请附上出处链接及本声明。来自:https://u1s1.vip/archives/166
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇