Peewee - 過濾器



可以使用 where 子句從 SQLite 表中檢索資料。Peewee 支援以下邏輯運算子列表。

== x 等於 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)

以下程式碼顯示年齡大於等於 20的姓名:

rows=User.select().where (User.age>=20)
for row in rows:
   print ("name: {} age: {}".format(row.name, row.age))

以下程式碼僅顯示 names 列表中存在的那些名稱。

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)

NOT IN 查詢。

3

.is_null(is_null)

IS NULL 或 IS NOT NULL。接受布林引數。

4

.contains(substr)

子字串的萬用字元搜尋。

5

.startswith(prefix)

搜尋以 prefix 開頭的值。

6

.endswith(suffix)

搜尋以 suffix 結尾的值。

7

.between(low, high)

搜尋 low 和 high 之間的值。

8

.regexp(exp)

正則表示式匹配(區分大小寫)。

9

.iregexp(exp)

正則表示式匹配(不區分大小寫)。

10

.bin_and(value)

二進位制 AND。

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 in 運算子。

  • & 代替 and。

  • | 代替 or。

  • ~ 代替 not。

  • .is_null() 代替 is。

  • None 或 == None。

廣告
© . All rights reserved.