peewee
3.17.8
Peewee 是一个简单且小型的 ORM。它的概念很少(但富有表现力),因此易于学习且直观易用。
刚接触小便?这些可能有帮助:
定义模型类似于 Django 或 SQLAlchemy:
from peewee import *
import datetime
db = SqliteDatabase ( 'my_database.db' )
class BaseModel ( Model ):
class Meta :
database = db
class User ( BaseModel ):
username = CharField ( unique = True )
class Tweet ( BaseModel ):
user = ForeignKeyField ( User , backref = 'tweets' )
message = TextField ()
created_date = DateTimeField ( default = datetime . datetime . now )
is_published = BooleanField ( default = True )
连接数据库并创建表:
db . connect ()
db . create_tables ([ User , Tweet ])
创建几行:
charlie = User . create ( username = 'charlie' )
huey = User ( username = 'huey' )
huey . save ()
# No need to set `is_published` or `created_date` since they
# will just use the default values we specified.
Tweet . create ( user = charlie , message = 'My first tweet' )
查询具有表达性和可组合性:
# A simple query selecting a user.
User . get ( User . username == 'charlie' )
# Get tweets created by one of several users.
usernames = [ 'charlie' , 'huey' , 'mickey' ]
users = User . select (). where ( User . username . in_ ( usernames ))
tweets = Tweet . select (). where ( Tweet . user . in_ ( users ))
# We could accomplish the same using a JOIN:
tweets = ( Tweet
. select ()
. join ( User )
. where ( User . username . in_ ( usernames )))
# How many tweets were published today?
tweets_today = ( Tweet
. select ()
. where (
( Tweet . created_date >= datetime . date . today ()) &
( Tweet . is_published == True ))
. count ())
# Paginate the user table and show me page 3 (users 41-60).
User . select (). order_by ( User . username ). paginate ( 3 , 20 )
# Order users by the number of tweets they've created:
tweet_ct = fn . Count ( Tweet . id )
users = ( User
. select ( User , tweet_ct . alias ( 'ct' ))
. join ( Tweet , JOIN . LEFT_OUTER )
. group_by ( User )
. order_by ( tweet_ct . desc ()))
# Do an atomic update (for illustrative purposes only, imagine a simple
# table for tracking a "count" associated with each URL). We don't want to
# naively get the save in two separate steps since this is prone to race
# conditions.
Counter . update ( count = Counter . count + 1 ). where ( Counter . url == request . url )
查看示例 Twitter 应用程序。
查看文档以获取更多示例。
具体问题?欢迎加入 irc.libera.chat 上的 #peewee 频道,或发布到邮件列表 http://groups.google.com/group/peewee-orm 。如果您想报告错误,请在 GitHub 上创建新问题。
我写了很多关于使用 peewee(通常是 Flask)构建应用程序和 Web 服务的博客文章。如果您想查看一些使用 peewee 的实际应用程序,以下资源可能会有用: