django ORM經常使用的查詢總結

假設模型名字爲Book,字段有id,name(char),page_nums(int),publication_date(datatime), readcount(int), commentcount(int)django

1.基礎查詢less

Book.objects.get(id=1)
Book.objects.filter(page_num > 100)
Book.objects.all() /Book.object.count()

2.模糊查詢函數

# 書名包含「西遊」
Book.objects.filter(name__contains='西遊')

# 書名以「龍」開頭
Book.objects.filter(name__startswith='')

# 書名以「族」結尾
Book.objects.filter(name__endswith='')

3.範圍,比較,空查詢spa

gt大於 (greater then)
gte大於等於 (greater then equal)
lt小於 (less then)
lte小於等於 (less then equal)

Book.objects.filter(id__in=[1,35])

Book.objects.filter(id__gt=3)

Book.objects.filter(name__isnull=True)

4.日期查詢code

查詢2019年發行的圖書
Book.objects.filter(publication_date__year=2019)
查詢2018年之後發行的圖書
Book.objects.filter(pub_date__gt='2018-1-1')

5.F對象與Q對象對象

from django.db.models import F, Q
經常使用查詢爲與常量的比較,當自己的兩個屬性進行比較時須要用到F對象,例如查詢閱讀量大於評論量的書籍
Book.objects.filter(readcount__gt=F('commentcount'))
並且能夠進行運算,例如閱讀量大於五倍評論量的書籍
Book.objects.filter(readcount__gt=F('commentcount')*5)
當表示多個過濾器之間的聯合查詢時,「and」能夠正常查詢,但「or」須要使用Q對象,例如
閱讀量大於1000且發行時間爲2018年之後
Book.objects.filter(readcount__gt=1000, publication_date__gt='2018-1-1') / Book.objects.filter(readcount__gt=1000).filter(publication_date__gt='2018-1-1')
表示""時只能使用Q對象 閱讀量大於1000或評論量大於200 Book.objects.filter(Q(readcount__gt=1000)|Q(commentcount__gt=200))

Q對象能夠再前面加上一個「~」表示「非」,例如,發行時間不是2019年的圖書
Book.objects.filter(~Q(publication_date__year=2019))

6.聚合查詢與排序blog

Avg平均,Count數量,Max最大,Min最小,Sum求和
調用聚合函數須要使用aggregate()過濾器,其返回值爲一個字典類型,但Count通常不使用,例如,

from django.db.models import Sum, Avg, Count, Max, Min
查詢閱讀量的總和,返回爲字典

Book.objects.aggregate(Sum('readcount'))
>>> {'readcount__sum': 12345}

查詢一共有多少本書,返回爲數字
Book.objects.count() / Book.objects.all().count()
>>> 123

按照閱讀量排序,降序能夠在查詢字段前面加上一個「-」來表示
Book.objects.all()。order_by("readcount")
Book.objects.all()。order_by("-readcount")

 

7.關聯查詢排序

當模型使用外鍵時就就須要使用關聯查詢,這裏添加一張新的關聯表-做者一個做者對應多個圖書:Author [id, name(char), book(ForeignKey)]ip

由一到多的訪問語法:一對應的模型類對象.多對應的模型類名小寫_set,例如
查詢名字爲裟欏雙樹做者的全部書籍,將返回一個包含全部書籍對象的查詢集
>>> author = Author.objects.get(name=「裟欏雙樹」)
>>> author.book_set.all()
由多到一的訪問語法:多對應的模型類對象.多對應的模型類中的關係類屬性名
查詢浮生物語書籍的做者
book= Book.objects.get(name=「浮生物語」)
book.author

關聯過濾查詢

8.Django中外鍵詳解get

 

9.Django中的查詢集(QuerySet)介紹

相關文章
相關標籤/搜索