從數據庫中查詢出來的結果通常是一個集合,這個集合叫作 QuerySetpython
.query.__str__()或 .query屬性打印執行的sql語句react
from quicktool.models import User from django.http import HttpResponse Creat = User.objects.all().filter(created=1557222940).query.__str__() return HttpResponse(str(Creat)) #輸出結果:SELECT `user`.`表字段1`, `user`.`表全部字段`, FROM `user` WHERE `user`.`created` = 1557222940
進入Django的manage.py所在目錄執行 python manage.py shell 進入shell模式正則表達式
C:\Users\admin>d: D:\>cd D:\django_test\mytestsite D:\django_test\mytestsite>python manage.py shell Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>>
* 3.1 普通的模型對象sql
普通的模型對象---用shell模式打印結果shell
>>> from quicktool.models import User >>> TodayCreat = User.objects.filter(created=1488356162) >>> print(type(TodayCreat)) <class 'django.db.models.query.QuerySet'> >>> print(TodayCreat) <QuerySet [<User: User object (63)>]>
普通的模型對象---用視圖網址展現結果數據庫
from quicktool.models import User from django.http import HttpResponse def TodayCreat(request): TodayCreat = User.objects.filter(created=1488356162) return HttpResponse(TodayCreat) # 瀏覽器展現結果:User object (63)
* 3.2 values()django
values()返回一個ValuesQuerySet(QuerySet的一個子類),迭代時返回字典,而不是模型實例對象
每一個字典表示一個對象,鍵對應於模型對象的屬性名稱瀏覽器
>>> from quicktool.models import User >>> TodayCreat = User.objects.filter(created=1488356162).values() >>> print(type(TodayCreat)) <class 'django.db.models.query.QuerySet'> >>> print(TodayCreat) <QuerySet [{'id':63, 'name':'xili','sex':'男'}]>
values()返回字典---用視圖網址展現結果函數
from quicktool.models import User from django.http import HttpResponse def TodayCreat(request): TodayCreat = User.objects.filter(created=1488356162).values() return HttpResponse(TodayCreat) # 瀏覽器展現結果:{'id':63, 'name':'xili','sex':'男'}
values(*fields),指定過濾哪些字段,返回的字典將只包含指定的字段的鍵和值ui
若是沒有指定字段,返回的每一個字典將包含數據表中全部字段的鍵和值
>>> from quicktool.models import User >>> TodayCreat = User.objects.filter(created=1488356162).values('id','name') >>> print(type(TodayCreat)) <class 'django.db.models.query.QuerySet'> >>> print(TodayCreat) <QuerySet [{'id': 63, 'name': 'xili'}]>
values(*fields)返回字典---用視圖網址展現結果
from quicktool.models import User from django.http import HttpResponse def TodayCreat(request): TodayCreat = User.objects.filter(created=1488356162).values('id','name') return HttpResponse(TodayCreat) # 瀏覽器展現結果:{'id':63, 'name':'xili'}
* 3.3 values_list()
values_list()迭代時返回元組,而不是字典
>>> from quicktool.models import User >>> TodayCreat = User.objects.filter(created=1488356162).values_list() >>> print(type(TodayCreat)) <class 'django.db.models.query.QuerySet'> >>> print(TodayCreat) <QuerySet [(63, 'xili','男')]>
values_list()返回元組---用視圖網址展現結果
from quicktool.models import User from django.http import HttpResponse def TodayCreat(request): TodayCreat = User.objects.filter(created=1488356162).values() return HttpResponse(TodayCreat) # 瀏覽器展現結果:(63,'xili','男')
values_list(*fields),指定過濾哪些字段,返回的元組將只包含指定的字段的鍵和值
若是沒有指定字段,返回的每一個元組將包含數據表中全部字段的鍵和值
>>> from quicktool.models import User >>> TodayCreat = User.objects.filter(created=1488356162).values_list('id','name') >>> print(type(TodayCreat)) <class 'django.db.models.query.QuerySet'> >>> print(TodayCreat) <QuerySet [(63, 'xili')]>
values_list(*fields)傳字段參數,不傳flat參數,返回元組---用視圖網址展現結果
from quicktool.models import User from django.http import HttpResponse def TodayCreat(request): TodayCreat = User.objects.filter(created=1488356162).values('id','name') return HttpResponse(TodayCreat) # 瀏覽器展現結果:(63,'xili')
values_list(*fields),*fields若是隻傳遞一個字段,則能夠傳遞flat參數爲True,它表示返回的結果爲單個值,而不是元組。
>>> from quicktool.models import User >>> TodayCreat = User.objects.filter(created=1488356162).values_list('name',flat=True) >>> print(type(TodayCreat)) <class 'django.db.models.query.QuerySet'> >>> print(TodayCreat) <QuerySet ['xili']>
values_list(*fields)既傳字段參數又傳flat參數,返回元組---用視圖網址展現結果
from quicktool.models import User from django.http import HttpResponse def TodayCreat(request): TodayCreat = User.objects.filter(created=1488356162).values('name',flat=True) return HttpResponse(TodayCreat) # 瀏覽器展現結果:xili
注:values_list(*fields),*fields若是傳遞了多個字段,再傳遞flat則會報錯
TypeError: 'flat' is not valid when values_list is called with more than one field.
>values和values_list返回結果類型上的差異:
* vlaues -
單條記錄 - <class 'dict'>
多條記錄 - <class 'django.db.models.query.QuerySet'>
* vlaues_list -
單條記錄 - <class 'tuple'>
多條記錄 - <class 'django.db.models.query.QuerySet'>
# all():查詢全部結果 Person.objects.all() # 查詢全部的Person條目 Person.objects.all()[:10] #切片操做,獲取10我的,不支持負索引,切片能夠節約內存,不支持負索引 # get(**kwargs):返回與所給篩選條件相匹配的對象,返回結果有且只有一個,若是符合篩選條件的對象超過一個或者沒有都會拋出錯誤 Person.objects.get(name="xili") # 名稱爲 xili的一條,多條會報錯 # filter(**kwargs):返回與所給篩選條件相匹配的對象 Person.objects.filter(name="abc") # 等於Person.objects.filter(name__exact="abc") 名稱嚴格等於 "abc" 的人 Person.objects.filter(name__iexact="abc") # 名稱爲 abc 可是不區分大小寫,能夠找到 ABC, Abc, aBC,這些都符合條件 Person.objects.filter(name__contains="abc") # 名稱中包含 "abc"的人 Person.objects.filter(name__icontains="abc") #名稱中包含 "abc",且abc不區分大小寫 Person.objects.filter(name__regex="^abc") # 正則表達式查詢 Person.objects.filter(name__iregex="^abc")# 正則表達式不區分大小寫 Person.objects .filter(creat__gt=1488356162) # creat時間大於某個時間戳 Person.objects .filter(creat__gte=1488356162) # creat時間大於等於某個時間戳 Person.objects .filter(creat__lt=1488356162) # creat時間小於某個時間戳 Person.objects .filter(creat__lte=1488356162) # creat時間小於等於某個時間戳 Person.objects .filter(creat__range=(start_time, end_time)) # creat時間在start_time和end_time範圍內 # exclude(**kwargs):返回與所給篩選條件不匹配的對象 Person.objects.exclude(name__contains="WZ") # 排除包含 WZ 的Person對象 Person.objects.filter(name__contains="abc").exclude(age=23) # 找出名稱含有abc, 可是排除年齡是23歲的
# order_by('-id')倒序,order_by('id')升序 # 元組升降序 User.objects.filter(Class_id=5).values_list('id').order_by('-id') 打印結果:(167,)(158,)(144,)(142,)(141,)(140,)(139,)(138,)(137,)(136,)(135,)(118,)(68,) User.objects.filter(Class_id=5).values_list('id').order_by('id') 打印結果:(68,)(118,)(135,)(136,)(137,)(138,)(139,)(140,)(141,)(142,)(144,)(158,)(167,) # 字典也能升降序 User.objects.filter(Class_id=5).values('id').order_by('id') 打印結果:{'id': 68}{'id': 118}{'id': 135}{'id': 136}{'id': 137}{'id': 138}{'id': 139}{'id': 140}{'id': 141}{'id': 142}{'id': 144}{'id': 158}{'id': 167}
Person.objects.all()[:10] #切片操做,前10條 Person.objects.all()[-10:] #會報錯!提示Negative indexing is not supported. # 1. 使用 reverse() 解決 Person.objects.all().reverse()[:2] # 最後兩條 Person.objects.all().reverse()[0] # 最後一條 # 2. 使用 order_by() 解決 Author.objects.order_by('-id')[:20] # id最大的20條
Plan.objects.all().filter(status=3).filter(created__lte=1557331200).filter(finished__gte=1557417599) User.objects.all().values('created').annotate(count=Count('created')).values('created','count') Person.objects.filter(name__contains="abc").exclude(age=23)
① distinct():從返回結果中剔除重複紀錄
qs1 = Pathway.objects.filter(label__name='x') qs2 = Pathway.objects.filter(reaction__name='A + B >> C') qs3 = Pathway.objects.filter(inputer__name='xili') # 合併到一塊兒 qs = qs1 | qs2 | qs3 這個時候就有可能出現重複的 # 去重方法 qs = qs.distinct()
② set():python內置函數,建立一個無序不重複的集合
select_UserID = Pathway.objects.filter(inputer__name='xili') set(select_UserID)
select_UserID = Pathway.objects.filter(inputer__name='xili') list(select_UserID) #結果打印[(532,), (671,), (797,), (532,)] #原先未轉變前打印((532,), (671,), (797,), (532,))
① count():返回數據庫中匹配查詢(QuerySet)的對象數量
User.objects.all().filter(created__range=(today_start_time, today_end_time)).count()
② len():將元組、字典或list統計元素個數
select_UserID = Pathway.objects.filter(inputer__name='xili') len(select_UserID)
Pathway.objects.filter(inputer__name='xili').first() Pathway.objects.filter(inputer__name='xili').last()
from quicktool.models import User from django.http import HttpResponse TodayCreat = User.objects.all().filter(created__range=(today_start_time, today_end_time)).exists() return HttpResponse(count_TodayCreat) #能查詢出數據則結果爲True,不能查詢出數據則返回False
es = Entry.objects.all() for e in es: print(e.headline)