django中的filter詳解

2022-03-17 22:50:09 字數 1192 閱讀 9923

我們很少會一次性從資料庫中取出所有的資料;通常都只針對一部分資料進行操作。 在django api中,我們可以使用`` filter()`` 方法對資料進行過濾:

>>> publisher.objects.filter(name='

apress')

filter()

根據關鍵字引數來轉換成 where

sql語句。 前面這個例子 相當於這樣:

select id, name, address, city, state_province, country, website

from books_publisher

where name = 'apress';

你可以傳遞多個引數到 filter()

來縮小選取範圍:

>>> publisher.objects.filter(country="

u.s.a.

", state_province="ca"

)[]

多個引數會被轉換成 and

sql從句, 因此上面的**可以轉化成這樣:

select id, name, address, city, state_province, country, website

from books_publisher

where country = '

u.s.a.

'and state_province = '

ca';

注意,sql預設的 =

操作符是精確匹配的, 其他型別的查詢也可以使用:

>>> publisher.objects.filter(name__contains="

press")

在 name 和 contains

之間有雙下劃線。和python一樣,django也使用雙下劃線來表明會進行一些魔術般的操作。這裡,contains

部分會被django翻譯成like

語句:

select id, name, address, city, state_province, country, website

from books_publisher

where name like

'%press%

';

Django的models中filter的各種用法

exact 精確等於 like aaa iexact 精確等於 忽略大小寫 ilike aaa contains 包含 like aaa icontains 包含 忽略大小寫 ilike aaa 但是對於sqlite來說,contains的作用效果等同於icontains。gt 大於 gte 大於等...

django中models的filter過濾方法

gte 大於等於 lt 小於 lte 小於等於 in 存在於乙個list範圍內 startswith 以 開頭 istartswith 以 開頭忽略大小寫 endswith 以 結尾 iendswith 以 結尾,忽略大小寫 range 在 範圍內 year 日期欄位的年份 month 日期欄位的月...

Filter函式詳析

select filter product category members,measures dollar sales 900000 and measures unit sales 90000 on axis 0 from sales where time 2005 measures dollar...