django模型系統二

經常使用查詢及表關係的實現python

1.經常使用查詢sql

每個django模型類,都有一個默認的管理器 objects數據庫

QuerySet表示數據庫中對象的列表,它能夠有0到多個過濾器。過濾器經過給定參數,縮小查詢範圍。django

QuerySet等同於select語句,過濾器是一個限制子句,好比where,limit。less

  all() 獲取全部函數

Student.objects.all()    #返回的是queryset

  獲取第一條spa

 Student.objects.first()  #返回的是對象

  獲取最後一條對象

Student.objects.last()    #返回的是對象

  get(**kwargs)根據給定的條件獲取一個對象,若是符合多個或沒有就會報錯blog

  filter(**kwargs)過濾,根據參數提供的條件,獲取一個過濾器後的QuerySet,多個條件等同於select子句使用and鏈接,關鍵字的參數的形參必須是模型中的字段名。排序

  

Student.objects.filter(name='張三').filter(sex=0)

  exclude(**kwargs)用法和filter同樣,做用相反,它是排除

  order(*fileds),根據給定的字段排序

res.order_by('-age','name')   #默認asc, -age表明反向排序

  切片:使用列表的切片語法操做query,除了不能用負索引,其餘均可以,他等價於LIMIT與OFFSET子句

  values(*fileds)返回queryset,這個queryset返回的是一個字典列表,參數fields指定了select中咱們想要限制查詢的字段。返回的字典列表中,只會包含咱們指定的字段。若是不指定,包含全部字段。

res=Student.objects.values('name')    

  only(*fileds)返回一個queryset,跟values同樣,區別在於這個queryset是對象列表,only必定包含主鍵。

res=Student.objects.only('name')  

  defer(*fields)用法與only相反

res=Student.objects.defer('sex')  

  多條件OR鏈接,須要實現OR條件,咱們要使用Q對象

from django.db.models import Q 
res=Student.objects.filter(Q(age=18)|Q(age=19)).only('name') 
等價於下面的sql:
SELECT `teacher_student`.`id`, `teacher_student`.`name` FROM `teacher_student` WHERE
(`teacher_student`.`age` = 18 OR `teacher_student`.`age` = 19)

  查詢條件:

  exact  精確匹配    

 res=Student.objects.filter(name__exact='張三')  

  iexact  忽略大小寫

res=Student.objects.filter(name__iexact='張三')  

  contains

res=Student.objects.filter(name__contains='張三')  

  icontains

  in

res=Student.objects.filter(name__in=[18,20])

  gt  (great than)

  gte  (great than equal)

res=Student.objects.filter(name__gte=18) 

  lt  (less than)

res=Student.objects.filter(name__lt=18)  

  lte

  startswith  以什麼開始

res=Student.objects.filter(name__startswith='張')   

  istartswith

  endwith     以什麼結尾

  iendwith

  range  範圍區間

res=Student.objects.filter(name__range=(18,20)) 

  isnull

res=Student.objects.filter(name__isnull=True)   

語法都是field__condition 是兩個下劃線

count返回queryset的長度

 

聚合函數

Avg

#計算同窗們的年齡平均值
res=Student.objects.aggregate(age_avg=Avg('age'))  

Max最大值

#找到年齡最大的學生
res=Student.objects.aggregate(age_max=Max('age'))  

Min最小值

sum求和

分組,聚合,分組須要結合values,annotate和聚合方法看下面的案例

#查詢男生女生分別有多少人
from django.db.models import Count 

res=Student.objects.values('sex').annotate(Count('sex'))

2.經常使用模型字段類型

參考官方文檔

https://docs.djangoproject.com/en/2.1/ref/models/fields/#field-types

 3.表關係實現

django中,模型經過特殊的字段進行關係鏈接。

一對一

一對多

多對多

相關文章
相關標籤/搜索