在 Python
的 ORM
框架中,比较主流的有 Sqlalchemy
,peewee
,pony
等等。但是其中 peewee
和 Django
的 Models
框架很像,如果了解 Django
的同学肯定对 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
表。
# 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()
# 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)
# 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)
# 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
以上就是今天的全部内容了,感谢您的阅读,我们下节再会。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有