1. 程式人生 > 其它 >python測試開發django-171.ORM查詢之exact和iexact

python測試開發django-171.ORM查詢之exact和iexact

前言

平常用ORM大部分使用的是get、filter、exclude這三種能滿足基本的需求。
ORM 條件查詢使用field__結合 condition 的方式來使用的,本篇講解下exact和iexact 在使用上有什麼區別。

exact 精準查詢

exact使用精確的 = 查詢,如果傳None引數,在SQL 中會被解釋為 NULL

>>> Product.objects.filter(name__exact='yy')
<QuerySet [<Product: Product object (2)>, <Product: Product object (5)>]>
>>> Product.objects.filter(name__exact=None)
<QuerySet []>

上面兩個查詢可以等價於以下SQL

select * from yoyo_product where name='yy'; 
select * from yoyo_product where name is NULL; 

filter(name__exact='yy') 實際上是等價於 filter(name='yy')

iexact 使用 like 查詢

iexact 使用 like 查詢,如

>>> Product.objects.filter(name__iexact='yy')
<QuerySet [<Product: Product object (2)>, <Product: Product object (5)>]>

上面查詢可以等價於以下SQL

select * from yoyo_product where name like 'yy'; 

exact 和 iexact區別

exact 和 iexact 的區別實際上就是 = 和 LIKE 的區別
這兩個引數會受到你的SQL的所在的安裝系統有關係。如果你的是Window系統,那麼就會不區分大小寫,相反Linux下是區分大小寫的。
這兩個引數還受你的資料庫的排序規則的這個引數影響。在大部分collation=utf8_general_ci 情況下都是一樣的(collation 是用來對字串比較的)
實際開發中使用 exact 和 iexact 很少,直接使用:field=xx 即可