Peewee – 过滤器
通过使用where子句,可以从SQLite表中获取数据。Peewee支持以下逻辑运算符列表。
== |
x等于y |
---|---|
< |
x小于y |
<= |
x小于或等于y |
> |
x大于y |
>= |
x 大于或等于y |
!= |
x不等于y |
<< |
x IN y,其中y是一个列表或查询 |
>> |
x是y,其中y是无/NULL |
% |
x LIKE y,其中y可以包含通配符 |
** |
x ILIKE y,其中y可能包含通配符 |
^ |
x XOR y |
~ |
一元否定(例如,NOT x)。 |
以下代码显示 **age>=20的 **名字:
rows=User.select().where (User.age>=20)
for row in rows:
print ("name: {} age: {}".format(row.name, row.age))
以下代码只显示名字列表中的那些名字。
names=['Anil', 'Amar', 'Kiran', 'Bala']
rows=User.select().where (User.name << names)
for row in rows:
print ("name: {} age: {}".format(row.name, row.age))
这样由Peewee生成的SELECT查询将是–
('SELECT "t1"."id", "t1"."name", "t1"."age" FROM "User" AS "t1" WHERE
("t1"."name" IN (?, ?, ?, ?))', ['Anil', 'Amar', 'Kiran', 'Bala'])
结果的输出将如下 –
name: Amar age: 20
name: Kiran age: 19
过滤方法
除了上述在Python核心中定义的逻辑运算符外,Peewee还提供了以下的过滤方法 –
序号 | 方法和描述 |
---|---|
1 | .in_(value) IN查找(与<<相同)。 |
2 | .not_in(value) 不包含在查询中。 |
3 | . is_null(is_null) IS NULL或IS NOT NULL。接受布尔型参数。 |
4 | .contains(substr) 对子串进行通配符搜索。 |
5 | .startwith(prefix) 搜索以prefix开头的值。 |
6 | .endwith(suffix) 搜索以后缀结束的数值。 |
7 | .between(low, high) 搜索介于low和high之间的值。 |
8 | . regexp(exp) 正则表达式匹配(区分大小写)。 |
9 | .iregexp(exp) 正则表达式匹配(不区分大小写)。 |
10 | .bin_and(value) 二进制和。 |
11 | .bin_or(value) 二进制OR。 |
12 | . concat(other) 使用||将两个字符串或对象连接起来。 |
13 | . distinct() 为DISTINCT选择标记列。 |
14 | . collate(collation) 用给定的整理方式指定列。 |
15 | .cast(type) 将列的值转换为给定的类型。 |
作为上述方法的一个例子,请看下面的代码。它检索了以’R’开头或以’r’结尾的名字。
rows=User.select().where (User.name.startswith('R') | User.name.endswith('r'))
相等的SQL SELECT查询是::
('SELECT "t1"."id", "t1"."name", "t1"."age" FROM "User" AS "t1" WHERE
(("t1"."name" LIKE ?) OR ("t1"."name" LIKE ?))', ['R%', '%r'])
替代方法
Python的内置运算符in, not in, and, or等将无法工作。相反,使用Peewee的替代品。
你可以使用-
-
.in_()和.not_in()方法来代替in和not的运算符。
-
用&代替and。
-
|代替or。
-
~代替not。
-
.is_null()代替is。
-
无或==无。