1. contains: 進行大小寫敏感的判斷,某個字符串是否包含在指定的字段中,這個判斷條件使用大小寫敏感進行判斷,所以在被翻譯成「SQL」語句的時候,會使用「like binary」, 而「like binary」就是使用大小寫敏感進行判斷。
2. icontains: 進行大小寫不敏感的判斷,某個字符串是否包含在指定的字段中,這個判斷條件使用大小寫不敏感進行判斷,所以在被翻譯成「SQL」語句的時候,會使用「like」, 而「like」就是使用大小寫不敏感進行判斷。其中icontains前面的i指的就是ignore(忽略)。
具體實例,示例代碼以下:
models.py文件中模型的定義,示例代碼以下:
from django.db import models
class Article(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
# 重寫類的__str__(self)方法
def __str__(self):
return "<(Article: id: %s,title: %s, content: %s)>" % (self.id, self.title, self.content)
# 從新定義表的一些屬性,注意:此處的類的名字必定要爲Meta
class Meta:
db_table = 'article'
1. contains: views.py文件中視圖函數的示例代碼以下:
from django.http import HttpResponse
from .models import Article
def index(request):
# 注意:此處是使用filter(),只有使用filter()以後纔可以在article(QuerySet)上調用query屬性,查看django底層轉化的sql語句。
article = Article.objects.filter(title__contains='hello')
print(article)
print(article.query)
return HttpResponse('success !')
在mysql數據庫中article表的數據信息以下:
![在這裏插入圖片描述](http://static.javashuo.com/static/loading.gif)
由於contains進行的是大小寫敏感的查找,因此不能找到匹配的數據,則會返回QuerySet爲空。而且咱們能夠看到執行咱們的查找條件的時候,django底層翻譯成的sql語句中的:WHERE
article.
titleLIKE BINARY %hello%
,這裏的LIKE BINARY 就能夠保證進行的查找爲大小寫敏感的查找,而且hello字符串的兩邊會有%(表明hello字符串前面能夠含有別的字符,後面也能夠含有別的字符),這就能夠驗證咱們上面的解釋。
![在這裏插入圖片描述](http://static.javashuo.com/static/loading.gif)
2.icontains: views.py文件中視圖函數示例代碼以下:
from django.http import HttpResponse
from .models import Article
def index(request):
# icontains進行查找title中包含「hello」的字符串
article = Article.objects.filter(title__icontains='hello')
print(article)
print(article.query)
return HttpResponse("success")
由於使用icontains採用的是大小寫不敏感的的查找方式,因此會返回兩條知足條件的QuerySet,而且重如下打印的結果中能夠看出,咱們的查詢條件被翻譯成了:WHERE
article.
titleLIKE %hello%
,這裏的LIKE進行的查找就是大小寫不敏感的查找。
![在這裏插入圖片描述](http://static.javashuo.com/static/loading.gif)
總結:iexact和exact進行的是準確性的查找,只有徹底匹配咱們的值「hello」的時候,纔可以被找到。而icontains和contains中的查詢條件,在進行查找的時候,會被翻譯成sql語句中包含「%hello%」,在這裏%意味着,前面能夠含有n個字符,後面也能夠含有n個字符。只要數據中包含hello字符串,就知足條件。