Python中的ORM工具:Peewee
阿新 • • 發佈:2018-12-11
上一篇文章介紹了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="[email protected]", 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: "[email protected]"}).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)
參考連結
示例原始碼 歡迎關注我的個人公眾號:超級碼里奧 如果這對您有幫助,歡迎點贊和分享,轉載請註明出處