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. [android 代码search地址]

    http://www.androidcodesearch.com/source/packages/apps/Settings/src/com/android/settings/SecuritySett ...

  2. Caffe 不同版本之间layer移植方法

    本系列文章由 @yhl_leo 出品,转载请注明出处. 文章链接: http://blog.csdn.net/yhl_leo/article/details/52185521 (前两天这篇博客不小心被 ...

  3. POJ 1971-Parallelogram Counting,暴力1063ms!

    Parallelogram Counting 刚学hash还不会用,看到5000ms的时限于是想着暴力来一发应该可以过.以前做过类似的题,求平行四边形个数,好像是在CF上做的,但忘了时限是多少了,方法 ...

  4. EasyUI 动态更新列

    function UpdateRow() { var rows = $('#tbpmgridList').datagrid('getChecked'); var productid = ''; for ...

  5. Hibernate get 和 load区别

    Session.load/get方法均可以根据指定的实体类和id从数据库读取记录,并返回与之对应的实体对象.下边详细说一下get和load的不同,因为有些时候为了对比也会把find加进来. 1.从返回 ...

  6. 【容斥】HDU 4135 Co-prime

    acm.hdu.edu.cn/showproblem.php?pid=4135 [题意] 询问[a,b]中与n互质的数有多少个 [思路] 考虑[1,m]中与n互质的数有多少个,答案就是query(b) ...

  7. System.out.println()和System.out.write()的区别

    这两个函数一个是System.out.write()输出字符流,System.out.println()是输出字节流,很简单.看下面这个程序就明白了.     //import java.util.* ...

  8. spring中quartz的使用。【转http://www.cnblogs.com/kay/archive/2007/11/02/947372.html】

    注:从spring3到spring4改变 org.springframework.scheduling.quartz.CronTriggerBean org.springframework.sched ...

  9. The Closest M Points BZOJ 3053

    The Closest M Points [问题描述] 软工学院的课程很讨厌!ZLC同志遇到了一个头疼的问题:在K维空间里面有许多的点,对于某些给定的点,ZLC需要找到和它最近的m个点. (这里的距离 ...

  10. hdu3491最小割转最大流+拆点

    题意:求最小割,即求最大流即可.此题之关键为拆点(限制在点),每条边都是双向边,注意一下. 未1A原因:在拆点之后添加边的过程中,要注意,出去的是i`,进来的是i,!!所以,写addegde函数时候 ...