Peewee作为Python ORM之一

优势:简单,小巧,易学习,使用直观

不足之处:需要手动创建数据库

基本使用流程

1⃣️根据需求定义好Model(表结构类)

2⃣️通过create_tables()创建表

示例:

 from peewee import *

 # 连接数据库
database = MySQLDatabase('test', user='root', host='localhost', port=3306) # 定义Person
class Person(Model):
name = CharField()
birthday = DateField()
is_relative = BooleanField() class Meta:
database = database
# 创建表
Person.create_table()
# 创建多个表
# database.create_tables([Person,
...])

技巧:已经创建好数据库表了,可以通过python -m pwiz脚本工具直接创建Model

# 指定mysql,用户为root,host为localhost,数据库为test
python -m pwiz -e mysql -u root -H localhost --password test > xModel.py
 from peewee import *

 database = MySQLDatabase('test', **{'charset': 'utf8', 'use_unicode': True, 'host': 'localhost', 'user': 'root', 'password': ''})

 class UnknownField(object):
def __init__(self, *_, **__): pass class BaseModel(Model):
class Meta:
database = database class Person(BaseModel):
birthday = DateField()
is_relative = IntegerField()
name = CharField() class Meta:
table_name = 'person'

PS关于数据类型:
CharField、DateField、BooleanField等这些类型与数据库中的数据类型一一对应,
我们直接使用它就行,至于CharField => varchar(255)这种转换Peewee已经为我们做好了。 增删改查操作:
一、增/插入数据
实例化一个Model
插入到数据库 1⃣️save()方法
# 插入一条数据
p = Person(name='xxx', birthday=date(1993, 1, 20), is_relative=True)
p.save()

  2⃣️insert()方法

# 插入一条数据
p_id = Person.insert({
'name': 'xxx'
}).execute() # 打印出新插入数据的id
print(p_id) 会返回新插入数据的主键

3⃣️insert_many() 多条插入

NUM = 10000
data = [{
'name': 'xxx'
} for i in range(NUM)] with database.atomic(): #事务
for i in range(0, NUM, 100):
# 每次批量插入100条,分成多次插入
Person.insert_many(data[i:i + 100]).execute()
二、查/查询数据
1⃣️get()获取单条数据
# 查询name为xxx的Person
p = Person.get(Person.name == 'xxx')
print(p.name) # 打印

2⃣️select()查询多条数据

# 查询Person整张表的数据
persons = Person.select()
# 遍历数据
for p in persons:
print(p.name, p.birthday, p.is_relative)

  3⃣️where()当做查询条件

# 获取is_relative为True的数据
persons = Person.select().where(Person.is_relative == True)
for p in persons:
print(p.name, p.birthday, p.is_relative) 通过sql()方法转换为SQL语句进行查看理解
persons = Person.select().where(Person.is_relative == True)
print(persons.sql())
# 打印出的结果为:('SELECT `t1`.`id`, `t1`.`name`, `t1`.`is_relative` FROM `Person` AS `t1` WHERE (`t1`.`is_relative` = %s)', [True])

4⃣️count()数据条数 order_by()排序 limit()限制数量

# 查询整张表的数据条数
total_num = Person.select().count() # 查询name为xxx的Person数量, 返回数量
num = Person.select().where(Person.name == 'xxx').count() # 按照主键id降序排序
persons = Person.select().order_by(Person.id.desc()) # 按照主键id升序排序
persons = Person.select().order_by(Person.id.asc()) # 相当于sql语句: select * from person order by id desc limit 5
persons = Person.select().order_by(Person.id.asc()).limit(5) # 相当于sql语句中:select * from person order by id desc limit 2, 5
persons = Person.select().order_by(Person.id.asc()).limit(5).offset(2)
三、改/更新数据
1⃣️当一个Model实例拥有主键时,此时使用save()就是修改数据
# 已经实例化的数据,指定了id这个primary key,则此时保存就是更新数据
p = Person(name='xxx', birthday=date(1993, 1, 20), is_relative=False)
p.id = 1
p.save()

2⃣️update()来更新数据,一般会搭配where()使用
# 更新birthday数据
q = Person.update({Person.birthday: date(1993, 1, 19)}).where(Person.name == 'xxx')
q.execute() q = Person.update({
'birthday': date(1993, 1, 19)
}).where(Person.name == 'xxx')
q.execute()

四、删/删除数据
1⃣️delete() + where()
# 删除姓名为xxx的数据
Person.delete().where(Person.name == 'xxx').execute()

2⃣️delete_instance()

# 已经实例化的数据, 使用delete_instance
p = Person(name='xxx', birthday=date(1993, 1, 20), is_relative=False)
p.id = 1
p.save()
p.delete_instance()
五、常用查询操作符
1⃣️容易理解
==、<、<=、>、>=、!=
等于、小于、小于等于、大于、大于等于、不等于
2⃣️需要关注

  <<>> 和 %

# <<使用,查询省份属于河北和河南的,对应sql语句:select * from person where province in ('河南', '河北')
persons = Person.select().where(Person.province << ['河南', '河北']) # >>使用,查询省份为空的,sql语句: select * from person where province is Null
persons = Person.select().where(Person.province >> None) # %使用,查询省份中含有 湖 字,sql语句:select * from person where province like '%湖%'
persons = Person.select().where(Person.province % '%湖%')
六、联表查询
query = (
Person.select(Person.content, Person.timestamp, Person.username)
.join(User, on=(User.id ==Person.user_id)
) for person in query:
print(person.content, person.timestamp, person.user.username) 换句话说就是:
将person里的user_id 绑定成一个‘User属性’,
查询时候直接当作一个属性对象拿取
person.user.username
七、事务
Database.atomic()方法
from xModels import XUser, database

with database.atomic() as transaction:
XUser.create(phone='xxxxxxxxxxx', password='')
XUser.create(phone='xxxxxxxxxx$', password='')

参考:http://docs.peewee-orm.com/en/latest/peewee/querying.html#querying

 

peewee 通俗易懂版的更多相关文章

  1. 转:怎么使用github(通俗易懂版)

    转:  https://www.zhihu.com/question/20070065 作者:珊姗是个小太阳链接:https://www.zhihu.com/question/20070065/ans ...

  2. TensorFlow入门(五)多层 LSTM 通俗易懂版

    欢迎转载,但请务必注明原文出处及作者信息. @author: huangyongye @creat_date: 2017-03-09 前言: 根据我本人学习 TensorFlow 实现 LSTM 的经 ...

  3. [网络必学]TCP/IP四层模型讲解【笔记整理通俗易懂版】

    OSI七层模型     表示层:用来解码不同的格式为机器语言,以及其他功能. 会话层:判断是否需要网络传输. 传输层:识别端口来指定服务器,如指定80端口的www服务. 网络层:提供逻辑地址选路,即发 ...

  4. TCP三次握手四次挥手,通俗易懂版

    三次握手四次挥手 三次握手 其实很好理解,三次握手就是保证双手都有发送和接受的能力.那么最少三次才能验证完成 即----> 客户端发送---服务端收到----服务端发送-- 1.客户端发送 -- ...

  5. 通俗易懂.NET GC垃圾回收机制(适用于小白面试,大牛勿喷)

    情景:你接到xx公司面试邀请,你怀着激动忐忑的心坐在对方公司会议室,想着等会的技术面试.技术总监此时走来,与你简单交谈后.... 技术:你对GC垃圾回收机制了解的怎么样? 你:还行,有简单了解过. 技 ...

  6. window.history

    作者:zccst 旧版: forword() backword() go(number) HTML5中新增了 onhashchange  浏览器兼容性较好,用得较多 pushState / repla ...

  7. GithubPages + Hexo + Disqus博客教程

    文章主要描述了利用github page,hexo静态博客框架以及disqus来搭建个人静态博客的详细步骤. github page用来搭建博客的主页,hexo用来更改博客主题.发布文章等等,并通过配 ...

  8. (译)理解 LSTM 网络 (Understanding LSTM Networks by colah)

    @翻译:huangyongye 原文链接: Understanding LSTM Networks 前言:其实之前就已经用过 LSTM 了,是在深度学习框架 keras 上直接用的,但是到现在对LST ...

  9. 转:TensorFlow入门(六) 双端 LSTM 实现序列标注(分词)

    http://blog.csdn.net/Jerr__y/article/details/70471066 欢迎转载,但请务必注明原文出处及作者信息. @author: huangyongye @cr ...

随机推荐

  1. socket 简单了解

    网络上的两个程序通过一个双向的通信连接实现数据的交换,这个连接的一端称为一个socket.   建立网络通信连接至少要一对端口号(socket).socket本质是编程接口(API),对TCP/IP的 ...

  2. 软件测试_Fiddler抓包工具二

    多数资料摘至:https://www.cnblogs.com/nihaorz/p/5455148.html Fiddler 的命令使用 如何打开命令行:左下方的小黑条命令行,点击它就可以输入命令了(a ...

  3. 【bug记录】OS Lab4 踩坑记

    OS Lab4 踩坑记 Lab4在之前Lab3的基础上,增加了系统调用,难度增加了很多.而且加上注释不详细,开玩笑的指导书,自己做起来困难较大.也遇到了大大小小的bug,调试了一整天. 本文记录笔者在 ...

  4. Scala基础

    1.seq[String] 用[]表示参数类型,java使用<>表示参数,因为Scala 允许以<命名方法和变量名,java不允许 2.支持range的类型:Char .Int . ...

  5. 安装netcat(-bash: netcat: command not found)

    安装netcat 在用swoole UDP服务器可以使用netcat -u 来连接测试时,报错-bash: netcat: command not found,是因为centos7未安装netcat. ...

  6. 18.25 JLink调试程序步骤

    S3C2440开发板启动时候选择NandFlash启动,然后输入如下命令: r                                 /*复位cpu*/ h                  ...

  7. [JAVA]字节数组流

    import java.io.*; public class ByteArrayStream { public static void main(String[] args) { byte[] dat ...

  8. golang操作memcached 转自https://blog.csdn.net/weixin_37696997/article/details/78760397

    go使用memcached需要第三方的驱动库,这里有一个库是memcached作者亲自实现的,代码质量效率肯定会有保障 1:安装 go get github.com/bradfitz/gomemcac ...

  9. MicrosoftRootCertificateAuthority2011.cer 下载

    下载地址:https://files.cnblogs.com/files/hyh123/microsoft-root-certificate-authority.rar 在安装Microsoft .N ...

  10. nginx ssl通讯优化思路

    TLS通讯过程中主要做的两件事情: 1.交换密钥 2.加密数据 如果优化的话,主要也是从这两个点来考虑优化: 1.nginx 打开session cache 如一天内不需要再次协商密钥. 2.小文件较 ...