1. 程式人生 > >django ORM常用查詢條件

django ORM常用查詢條件

等於 是否 title info bject tex query alt with

假設有一個模型

class Article(models.Model):
    title=models.CharField(max_length=50)
    content=models.TextField()
    class Meta:
        db_table=book

對於查詢結果是結果集,即通過filter進行查詢所得的對象來說,可通過query屬性來查看django轉換之後的原生sql語句

……
article=Article.objects.filter(title=Hello World)
    print(article.query)
    
print(article) ……

查詢結果為

技術分享圖片

exact:即相當於數據庫底層的等號=

article=Article.objects.filter(title_exact=‘Hello World‘),即相當於數據庫底層的select ··· from ··· where title=‘Hello World‘

iexact:即相當於數據庫底層的like

article=Article.objects.filter(title__iexact=‘Hello World‘),即相當於數據庫底層的select ··· from ··· where title like ‘Hello World‘

contains:大小寫敏感的匹配查詢,也是like,註意轉換後查詢條件的兩側都有%

article=Article.objects.filter(title__contains=‘Hello World‘),即相當於數據庫底層的select ··· from ··· where title like ‘%Hello World%‘

icontains:大小寫不敏感的匹配查詢

article=Article.objects.filter(title__icontains=‘Hello World‘),即相當於數據庫底層的select ··· from ··· where title like ‘%Hello World%‘

in:查詢條件是否在給定的範圍內,用小括號和中括號都可以

article=Article.objects.filter(id__in=(1,2,6,9)),即相當於數據庫底層的select ··· from ··· where id in (1,2,6,9)

gt:大於

gte:大於等於

lt:小於

lte:小於等於

article=Article.objects.filter(id__gt=5),即相當於數據庫底層的select ··· from ··· where id > 5

startswith:以指定某個字符串開始,大小寫敏感

istartswith:以指定某個字符串開始,大小寫不敏感

endswith:以指定某個字符串結束,大小寫敏感

iendswith:以指定某個字符串結束,大小寫不敏感

article=Article.objects.filter(title__startswith=‘Hello‘),即相當於數據庫底層的select ··· from ··· where title like ‘Hello%‘

article=Article.objects.filter(title__endswith=‘Hello‘),即相當於數據庫底層的select ··· from ··· where title like %‘Hello‘

range:在某個範圍,即相當於between ··· and ···,用小括號和中括號都可以

article=Article.objects.filter(id__range=(1,6)),即相當於select ··· from ··· where id between 1 and 6

isnull:是否為空

article=Article.objects.filter(content__isnull=False),即相當於select ··· from ··· where content is not null

django ORM常用查詢條件