可以使用 where 子句从 SQLite 表中检索数据。Peewee 支持以下逻辑运算符列表。
== | x 等于 y |
< | x 小于 y |
<= | x 小于或等于 y |
> | x 大于 y |
>= | x 大于或等于 y |
!= | x 不等于 y |
<< | x 属于 y,其中 y 是列表或查询 |
>> | x 是 y,其中 y 是 None/NULL |
% | x LIKE y 其中 y 可能包含通配符 |
** | x ILIKE y 其中 y 可能包含通配符 |
^ | x XOR y |
~ | 一元否定 (e.g., NOT x) |
以下代码显示年龄>=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 还提供以下过滤方法 -
Sr.No | 方法和说明 |
---|---|
1 | .in_(value) IN lookup (identical to <<). |
2 | .not_in(value) NOT IN lookup. |
3 |
.is_null(is_null) |
4 |
.contains(substr) |
5 |
.startswith(prefix) |
6 |
.endswith(suffix) |
7 |
.between(low, high) |
8 |
.regexp(exp) |
9 |
.iregexp(exp) |
10 |
.bin_and(value) |
11 |
.bin_or(value) |
12 |
.concat(other) |
13 |
.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、或 etc. 将不起作用。可以使用 Peewee 替代。
您可以使用 -
- .in_() 和 .not_in() 方法而不是 in 和 not in 运算符。
-
& 替代 and
-
| 替代 or
-
~ 替代 not.
-
.is_null() 替代 is.
-
None or == None.
酷客网相关文章:
评论前必须登录!
注册