Peewee

Python中数据库与ORM主要做这几件事:

  1. 数据库方面由程序员设计表关系,主要是1v1,1vN,NvN;
  2. ORM做数据类型映射,将数据库表示的char/int等类型映射成Python对象,将数据映射到Python类对象,将数据表关系映射到类关系中;
  3. 实现CRUD和事务语句转换,将转化的SQL语句传递给数据库引擎,并将结果返回转为类对象;
  4. 缓存优化,数据以对象的形式存储在内存中。

创建

from peewee import *
from datetime import date

db = SqliteDatabase('people.db')

class Person(Model):
    name = CharField()
    birthday = DateField()

    class Meta:
        database = db

with db:
    Person.create_table()

    bob = Person(name='bob', birthday=date(1990,1,1))
    bob.save()

    bob = Person.get(name == 'bob')
    print(bob.birthday)
# 其它数据库创建
from peewee import *

# SQLite database using WAL journal mode and 64MB cache.
sqlite_db = SqliteDatabase('/path/to/app.db', pragmas={
    'journal_mode': 'wal',
    'cache_size': -1024 * 64})

# Connect to a MySQL database on network.
mysql_db = MySQLDatabase('my_app', user='app', password='db_password',
                         host='10.1.0.8', port=3316)

# Connect to a Postgres database.
pg_db = PostgresqlDatabase('my_app', user='postgres', password='secret',
                           host='10.1.0.9', port=5432)

get方法只能获取唯一一条,获取多条通过filter()方法

数据类型
数据参数

查询

# 官方查询示例,返回的是迭代器
tweets = (Tweet
          .select(Tweet, User)
          .join(User)
          .order_by(Tweet.create_date.desc()))

插入

# 单条数据
res = (Facility
       .insert(facid=9, name='Spa', membercost=20, guestcost=30,
               initialoutlay=100000, monthlymaintenance=800)
       .execute())

# 上面插入单条等效于
res = Facility(facid=9, name='Spa', membercost=20, guestcost=30,
               initialoutlay=100000, monthlymaintenance=800)
res.save()

# 多条数据
data = [
    {'facid': 9, 'name': 'Spa', 'membercost': 20, 'guestcost': 30,
     'initialoutlay': 100000, 'monthlymaintenance': 800},
    {'facid': 10, 'name': 'Squash Court 2', 'membercost': 3.5,
     'guestcost': 17.5, 'initialoutlay': 5000, 'monthlymaintenance': 80}]
res = Facility.insert_many(data).execute()

更新数据

# 修改单列
res = (Facility
       .update(initialoutlay=10000)
       .where(Facility.name == 'Tennis Court 2')
       .execute())

# 修改多列
nrows = (Facility
         .update(membercost=6, guestcost=30)
         .where(Facility.name.startswith('Tennis'))
         .execute())

删除数据

nrows = Member.delete().where(Member.memid == 37).execute()

修改表定义

from playhouse.migrate import *

# 通过Migrator实例来修改
# Postgres example:
my_db = PostgresqlDatabase(...)
migrator = PostgresqlMigrator(my_db)

# SQLite example:
my_db = SqliteDatabase('my_database.db')
migrator = SqliteMigrator(my_db)

migrate(
    migrator.add_column('some_table', 'title', title_field),
    migrator.rename_column('story', 'mod_date', 'modified_date'),
    migrator.drop_column('some_table', 'old_column'),
    migrator.drop_not_null('story', 'pub_date'),
    migrator.rename_table('story', 'stories_tbl'),
    migrator.add_index('story', ('pub_date',), False),
    migrator.drop_index('story', 'story_pub_date_status'),
    migrator.create_index('some_table', ('new_column',)
)

详细

playhouse提供方法用于将对象转换成字典

from playhouse.shortcuts import model_to_dict, dict_to_model

d = model_to_dict(bob)
print(d)

peewee模块的更多相关文章

  1. Python有关模块学习记录

    1 pandas numpy模块 首先安装搭建好jupyter notebook,运行成功后的截图如下: 安装使用步骤(PS:确定Python安装路径和安装路径里面Scripts文件夹路径已经配置到环 ...

  2. peewee在flask中的配置

    # 原文:https://blog.csdn.net/mouday/article/details/85332510 Flask的钩子函数与peewee.InterfaceError: (0, '') ...

  3. tornado+peewee-async+peewee+mysql(一)

    前言: 需要异步操作MySQL,又要用orm,使用sqlalchemy需要加celery,觉得比较麻烦,选择了peewee-async 开发环境 python3.6.8+peewee-async0.5 ...

  4. peewee的简单使用

    peewee的简单使用 peewee是一个轻量级的ORM框架,peewee完全可以应对个人或企业的中小型项目的Model层,上手容易,功能强大. 一.安装peewee模块 使用pip命令工具安装pee ...

  5. python 第三方模块 转 https://github.com/masterpy/zwpy_lst

    Chardet,字符编码探测器,可以自动检测文本.网页.xml的编码. colorama,主要用来给文本添加各种颜色,并且非常简单易用. Prettytable,主要用于在终端或浏览器端构建格式化的输 ...

  6. [Python]peewee使用经验

    peewee 使用经验 本文使用案例是基于 python2.7 实现 以下内容均为个人使用 peewee 的经验和遇到的坑,不会涉及过多的基本操作.所以,没有使用过 peewee,可以先阅读文档 正确 ...

  7. python模块 - 常用模块推荐

    http://blog.csdn.net/pipisorry/article/details/47185795 python常用模块 压缩字符 当谈起压缩时我们通常想到文件,比如ZIP结构.在Pyth ...

  8. [Python]peewee 使用经验

    peewee 使用经验 本文使用案例是基于 python2.7 实现 以下内容均为个人使用 peewee 的经验和遇到的坑,不会涉及过多的基本操作.所以,没有使用过 peewee,可以先阅读文档 正确 ...

  9. python模块大全

    python模块大全2018年01月25日 13:38:55 mcj1314bb 阅读数:3049 pymatgen multidict yarl regex gvar tifffile jupyte ...

随机推荐

  1. 【Luogu】P3052摩天大楼里的奶牛(状压DP)

    参见ZHT467的题解. f[i]表示在i这个集合下的最少分组数和当前组最少的容量. 从1到(1<<n)-1枚举i,对于每个i枚举它的子奶牛,然后重载运算符计算. 代码如下 #includ ...

  2. HDU——1242Rescue(BFS+优先队列求点图最短路)

    Rescue Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others) Total Sub ...

  3. 【leetcode最短路】818. Race Car

    https://leetcode.com/problems/race-car/description/ 1. BFS剪枝 0<=current position<=2*target.为什么 ...

  4. Linux 下测试磁盘读写 I/O 速度的方法汇总

    在分布式异构存储系统中,我们经常会需要测量获取不同节点中硬盘/磁盘的读写 I/O 速度,下面是 Linux 系统下一些常用测试方法(之后不定期更新): 1.使用 hdparm 命令这是一个是用来获取A ...

  5. 【HDOJ5952】Counting Cliques(团,dfs)

    题意:给定一张n点m边的图,求大小为S的团的个数 N ≤ 100,M ≤ 1000,2 ≤ S ≤ 10,保证点的度不超过20 思路:dfs 因为每个点可能不止属于一个极大团,所以不能求出极大团然后计 ...

  6. C语言函数调用及栈帧结构

    source:http://blog.csdn.net/qq_29403077/article/details/53205010 一.地址空间与物理内存 (1)地址空间与物理内存是两个完全不同的概念, ...

  7. Laravel 数据库操作之Eloquent ORM模型

    //模型中的相关代码 namespace App; use Illuminate\Database\Eloquent\Model; class Student extends Model{ //默认对 ...

  8. laravel控制器

    //访问MemberController下的info的方法 //方法一//访问路径http://localhost/Laravel/public/member/infoRoute::get('memb ...

  9. postman 快捷方式--启动图标

    下载,解压,安装,(此安装位置在/opt) 1.创建全局变量,也就是在任何地方都可以执行postman,不用去到安装目录,执行 : sudo ln -s /opt/postman/Postman /u ...

  10. hdu 1754 splay tree伸展树 初战(单点更新,区间属性查询)

    题意:与区间查询点更新,点有20W个,询问区间的最大值.曾经用线段树,1000+ms,今天的伸展树,890没ms,差不多. 第一次学习伸展树,一共花了2个单位时间,感觉伸展树真很有用,也很好玩.现在只 ...