Peewee是一个易用轻巧的ORM。
Peewee is a simple and small ORM. It has few (but expressive) concepts, making it easy to learn and intuitive to use.
而ORM则是
对象关系映射(英语:Object Relational Mapping,简称ORM,或O/RM,或O/R mapping),是一种程序技术,用于实现面向对象编程语言里不同类型系统的数据之间的转换。从效果上说,它其实是创建了一个可在编程语言里使用的“虚拟对象数据库”。
官网来的示例很糟糕,一个简化的示例如下所示:
from peewee import *
import datetime
db = SqliteDatabase('my_database.db', threadlocals=True)
class BaseModel(Model):
class Meta:
database = db
不过,却也提供了几个很实用的模型构建脚本。
pwiz is a little script that ships with peewee and is capable of introspecting an existing database and generating model code suitable for interacting with the underlying data. If you have a database already, pwiz can give you a nice boost by generating skeleton code with correct column affinities and foreign keys.
类似的示例有一个:
python -m pwiz --engine=postgresql my_postgresql_database
而我是用它来生成WordPress的模型,于是有:
python -m pwiz -e mysql "MK_xunzhao" -uroot > blog_models.py
就这样我们生成了WordPress的Models
接着我们要做的就是一个简单的查询。
下面是WordPress的wp_posts生成的models
class WpPosts(BaseModel):
id = BigIntegerField(db_column='ID', primary_key=True)
comment_count = BigIntegerField()
comment_status = CharField()
guid = CharField()
menu_order = IntegerField()
ping_status = CharField()
pinged = TextField()
post_author = BigIntegerField(index=True)
post_content = TextField(index=True)
post_content_filtered = TextField()
post_date = DateTimeField()
post_date_gmt = DateTimeField()
post_excerpt = TextField()
post_mime_type = CharField()
post_modified = DateTimeField()
post_modified_gmt = DateTimeField()
post_name = CharField(index=True)
post_parent = BigIntegerField(index=True)
post_password = CharField()
post_status = CharField()
post_title = TextField(index=True)
post_type = CharField()
to_ping = TextField()
class Meta:
db_table = 'wp_posts'
而我们查询语句对应的便是:
blog_posts = WpPosts.select().where(
(WpPosts.post_status == "publish") &
(WpPosts.post_type == "post")
).offset(offset).limit(10)
围观我的Github Idea墙, 也许,你会遇到心仪的项目