Python 中的 ORM 工具:Peewee

上一篇文章介绍了Pyhton中的ORM工具:SQLAlchemy。本文延续之前的风格,介绍另一个ORM模块:Peewee,希望通过简单的CRUD示例可以帮助大家快速上手。

环境说明

  • python v3.6.5
  • peewee v3.7.0
  • faker v0.9.1(生成伪造数据)

安装环境

	pip install peewee faker

CRUD示例

同样的,Peewee也支持绝大多数关系型数据库,示例中使用的是PostgreSQL,用法及说明大多已在源代码中注释,请具体参考如下:

from peewee import *
from faker import Factory
from datetime import datetime

# Create an instance of a Database
db = PostgresqlDatabase(database="postgres", host="localhost",
                        port=5432, user="postgres", password="password", )


# Define a model class
class User(Model):
    # If none of the fields are initialized with primary_key=True,
    # an auto-incrementing primary key will automatically be created and named 'id'.
    id = PrimaryKeyField()
    email = CharField(index=True, max_length=64)
    username = CharField(unique=True, max_length=32)
    password = CharField(null=True, max_length=64)
    createTime = DateTimeField(column_name="create_time", default=datetime.now)

    class Meta:
        database = db
        table_name = 'tb_user'
        # If Models without a Primary Key
        # primary_key = False

    def __str__(self) -> str:
        return "User(id:{} email:{} username:{} password:{} createTime: {})".format(
            self.id, self.email, self.username, self.password, self.createTime)


db.connect()
db.drop_tables([User])
db.create_tables([User])

""" CREATE """

# 创建User对象
user = User(email="zs@123.com", username="张三", password="zs")
# 保存User
user.save()

# 创建faker工厂对象
faker = Factory.create()
# 利用faker创建多个User对象
fake_users = [{
    'username': faker.name(),
    'password': faker.word(),
    'email': faker.email(),
} for i in range(5)]
# 批量插入
User.insert_many(fake_users).execute()

""" RETRIEVE/GET/FIND """

user = User().select().where(User.id != 1).get()
print(user)
user = User.select().where(User.username.contains("张")).get()
print(user)
count = User.select().filter(User.id >= 3).count()
print(count)
users = User.select().order_by(User.email)
for u in users:
    print(u)

""" UPDATE """

effect_count = User.update({User.username: "李四", User.email: "ls@163.com"}).where(User.id == 1).execute()
print(effect_count)

""" DELETE """

effect_count = User().delete_by_id(6)
print(effect_count)
effect_count = User.delete().where(User.id >= 4).execute()
print(effect_count)

参考链接

peewee 3.7.0 documentation

示例源码
欢迎关注我的个人公众号:超级码里奥
如果这对您有帮助,欢迎点赞和分享,转载请注明出处

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值