当前位置:   article > 正文

Peewee | 优雅的ORM框架!

peewee csdn

Part1前言

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

Part2peewee 的世界

1安装

pip install peewee

2创建数据库&表

  1. from peewee import *
  2. from datetime import date
  3. from playhouse.migrate import *
  4. # 如果db不存在,会自动创建
  5. db = SqliteDatabase('pp.db')
  6. class people(Model):
  7.     # 默认会有ID作为主键自增
  8.     name = CharField()
  9.     birth = DateField()
  10.     people_status = BooleanField(default=True)
  11.     class Meta:
  12.         database = db
  13. # connect db
  14. db.connect()
  15. # create table
  16. db.create_tables([
  17.     people,
  18. ])
  19. close db
  20. db.close()

查看数据库

在当前路径下查看是否创建了 pp.db,是否在数据库中创建了 people 表。

创建的db
数据库&表在SQLitebrowser中

3CURD-C

  1. # add people
  2. phyger = people(name='phyger1',birth=date(1990,1,1))
  3. phyger.save()
  4. # Too
  5. pp = people.create(name='phyger2',birth=date(1991,1,2))
  6. pp.save()
增加的数据

4CRUD-R

  1. # search people
  2. res = people.get_by_id(1)
  3. print('ID为1的数据的name是:'res.name)
  4. # search all (list)
  5. ret = people.select()
  6. for i in ret:
  7.     print(i.id, i.name)
  8. # where
  9. rep = people.select().where(people.name == 'phyger2').get()
  10. print('name为phyger2的ID是:',rep.id)
  11. rea = people.select().where(people.people_status == True)
  12. for i in rea:
  13.     print(i.name)
查询的结果

5CRUD-U

  1. # update info
  2. rep = people.select().where(people.name == 'phyger2').get()
  3. # modify status
  4. rep.people_status=False
  5. # don't forget save
  6. rep.save()
  7. # search phyger2's status
  8. res = people.select().where(people.name == 'phyger2').get()
  9. print("phyger2's status is : ",res.people_status)
修改后的结果
SQLitebrowser中的结果

6CRUD-D

  1. delete info
  2. res = people.select().where(people.name == 'phyger1').get()
  3. res.delete_instance()
  4. res.save()
刪除后的效果

更多内容详见官方文档:

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

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

往期推荐

Partial | 超有用的偏函数

经典实践 | 网速测速小工具(上)

经典实践 | 网速测速小工具(下)

这个小工具竟然可以让我保持健康

Schedule | 轻量化的定时任务框架

肾模?你还不会sqlalchemy!【SQLite】

点个

在看

你最好看

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/172914
推荐阅读
相关标签
  

闽ICP备14008679号