Peewee 简明教程
Peewee - Filters
可以使用 where 子句从 SQLite 表中检索数据。Peewee 支持以下逻辑运算符列表。
== |
x equals y |
< |
x 小于 y |
⇐ |
x 小于或等于 y |
> |
x 大于 y |
>= |
x 大于或等于 y |
!= |
x 不等于 y |
<< |
x IN y,其中 y 为列表或查询 |
>> |
x IS y,其中 y 为 None/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
Filtering Methods
除了核心 Python 中定义的上述逻辑运算符之外,Peewee 还提供以下方法进行筛选 −
Sr.No |
Methods & Description |
1 |
.in_(value) IN 查找(与 << 标识)。 |
2 |
.not_in(value) NOT IN lookup. |
3 |
.is_null(is_null) IS NULL 或 IS NOT NULL。接受布尔参数。 |
4 |
.contains(substr) Wild-card search for substring. |
5 |
.startswith(prefix) 搜索以前缀开头的值。 |
6 |
.endswith(suffix) 以某个后缀结尾的值搜索。 |
7 |
.between(low, high) 在低和高之间值搜索。 |
8 |
.regexp(exp) Regular expression match (case-sensitive). |
9 |
.iregexp(exp) Regular expression match (case-insensitive). |
10 |
.bin_and(value) Binary AND. |
11 |
.bin_or(value) Binary 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'])