Skip to content

简介

Peewee是一个简单和小型的ORM。它很少(但表达)概念,使其易于学习和直观使用。

支持的数据库:

MySQL

PostgreSQL

SQLite

安装

python
pip install peewee

创建模型

创建blog.py文件存放模型

python
from datetime import datetime
from peewee import MySQLDatabase, Model, CharField, DateTimeField, BooleanField, ManyToManyField, IntegerField, TextField, DecimalField

db = MySQLDatabase(host='127.0.0.1', user='user', password='password', database='blog', charset='utf8')


class BaseModel(Model):
    """基础表"""
    delete_flag = BooleanField(default=False)
    create_time = DateTimeField(default=datetime.now)
    update_time = DateTimeField(default=datetime.now)

    class Meta:
        database = db


class Articles(BaseModel):
    """文章表"""
    title = CharField(max_length=64, verbose_name='文章标题')
    pic = CharField(max_length=128, verbose_name='标题图片')
    category = IntegerField(verbose_name='版块')
    summary = CharField(max_length=32, verbose_name='描述')
    content = TextField(verbose_name='正文内容')
    author = IntegerField(verbose_name='作者')
    hidden = BooleanField(default=False, verbose_name="隐藏")
    priority = IntegerField(default=1000, verbose_name='优先级')

写入数据库

创建0001_initial.py文件,模型生成对应表,写入数据库:

python
from models import blog

tables = [blog.Articles]
db = blog.db

try:
    db.connect()
    db.create_tables(tables)
except BaseException:
    db.rollback()
else:
    db.close()

tables是一个列表,是要创建的表模型。已经存在的表,会忽略。使用迁移功能修改表结构。

模型迁移

创建0002_alter.py文件,下面内容是修改表结构的一个例子:

python
from playhouse.migrate import *
from models import blog

db = blog.db
migrator = MySQLMigrator(db)

title_field = CharField(default='')
status_field = IntegerField(null=True)

migrate(
    migrator.add_column('some_table', 'title', title_field),
    migrator.rename_column('some_table', 'pub_date', 'publish_date'),
    migrator.add_column('some_table', 'status', status_field),
    migrator.drop_column('some_table', 'old_column'),
)

db.close()

更多用法

http://peewee.readthedocs.io/en/latest/