django_orm操做

查詢操做和性能優化

1.基本操做

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
  
 
models.Tb1.objects.create(c1 = 'xx' , c2 = 'oo' )  增長一條數據,能夠接受字典類型數據  * * kwargs
 
obj  =  models.Tb1(c1 = 'xx' , c2 = 'oo' )
obj.save()
 
 
 
models.Tb1.objects.get( id = 123 )          # 獲取單條數據,不存在則報錯(不建議)
models.Tb1.objects. all ()                # 獲取所有
models.Tb1.objects. filter (name = 'seven' # 獲取指定條件的數據
models.Tb1.objects.exclude(name = 'seven' # 獲取指定條件的數據
 
 
 
models.Tb1.objects. filter (name = 'seven' ).delete()  # 刪除指定條件的數據
 
 
models.Tb1.objects. filter (name = 'seven' ).update(gender = '0' )   # 將指定條件的數據更新,均支持 **kwargs
obj  =  models.Tb1.objects.get( id = 1 )
obj.c1  =  '111'
obj.save()                                                  # 修改單條數據

2.Foreign key的使用緣由

1
2
3
4
約束
節省硬盤
 
可是多表查詢會下降速度,大型程序反而不使用外鍵,而是用單表(約束的時候,經過代碼判斷)

extrapython

1
2
3
4
5
extra( self , select = None , where = None , params = None , tables = None , order_by = None , select_params = None )
    Entry.objects.extra(select = { 'new_id' "select col from sometable where othercol > %s" }, select_params = ( 1 ,))
    Entry.objects.extra(where = [ 'headline=%s' ], params = [ 'Lennon' ])
    Entry.objects.extra(where = [ "foo='a' OR bar = 'a'" "baz = 'a'" ])
    Entry.objects.extra(select = { 'new_id' "select id from tb where id > %s" }, select_params = ( 1 ,), order_by = [ '-nid' ])

F查詢django

1
2
from  django.db.models  import  F
    models.Tb1.objects.update(num = F( 'num' ) + 1 )

Q查詢性能優化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
方式一:
     Q(nid__gt = 10 )
     Q(nid = 8 ) | Q(nid__gt = 10 )
     Q(Q(nid = 8 ) | Q(nid__gt = 10 )) & Q(caption = 'root' )
 
     方式二:
     con  =  Q()
     q1  =  Q()
     q1.connector  =  'OR'
     q1.children.append(( 'id' 1 ))
     q1.children.append(( 'id' 10 ))
     q1.children.append(( 'id' 9 ))
     q2  =  Q()
     q2.connector  =  'OR'
     q2.children.append(( 'c1' 1 ))
     q2.children.append(( 'c1' 10 ))
     q2.children.append(( 'c1' 9 ))
     con.add(q1,  'AND' )
     con.add(q2,  'AND' )
 
     models.Tb1.objects. filter (con)

exclude(self, *args, **kwargs)app

1
2
# 條件查詢
    # 條件能夠是:參數,字典,Q

  

select_related(self, *fields)性能

1
2
3
4
性能相關:表之間進行join連表操做,一次性獲取關聯的數據。
     model.tb.objects. all ().select_related()
     model.tb.objects. all ().select_related( '外鍵字段' )
     model.tb.objects. all ().select_related( '外鍵字段__外鍵字段' )

 

prefetch_related(self, *lookups)fetch

1
2
3
4
性能相關:多表連表操做時速度會慢,使用其執行屢次SQL查詢  在內存中作關聯,而不會再作連表查詢
            # 第一次 獲取全部用戶表
            # 第二次 獲取用戶類型表where id in (用戶表中的查到的全部用戶ID)
            models.UserInfo.objects.prefetch_related( '外鍵字段' )

  

annotate(self, *args, **kwargs)優化

1
2
3
4
5
6
7
8
9
10
11
12
# 用於實現聚合group by查詢
 
     from  django.db.models  import  Count, Avg,  Max Min Sum
 
     =  models.UserInfo.objects.values( 'u_id' ).annotate(uid = Count( 'u_id' ))
     # SELECT u_id, COUNT(ui) AS `uid` FROM UserInfo GROUP BY u_id
 
     =  models.UserInfo.objects.values( 'u_id' ).annotate(uid = Count( 'u_id' )). filter (uid__gt = 1 )
     # SELECT u_id, COUNT(ui_id) AS `uid` FROM UserInfo GROUP BY u_id having count(u_id) > 1
 
     =  models.UserInfo.objects.values( 'u_id' ).annotate(uid = Count( 'u_id' ,distinct = True )). filter (uid__gt = 1 )
     # SELECT u_id, COUNT( DISTINCT ui_id) AS `uid` FROM UserInfo GROUP BY u_id having count(u_id) > 1

 

 

extra(self, select=None, where=None, params=None, tables=None, order_by=None, select_params=None)ui

1
2
3
4
5
6
# 構造額外的查詢條件或者映射,如:子查詢
 
       Entry.objects.extra(select = { 'new_id' "select col from sometable where othercol > %s" }, select_params = ( 1 ,))
       Entry.objects.extra(where = [ 'headline=%s' ], params = [ 'Lennon' ])
       Entry.objects.extra(where = [ "foo='a' OR bar = 'a'" "baz = 'a'" ])
       Entry.objects.extra(select = { 'new_id' "select id from tb where id > %s" }, select_params = ( 1 ,), order_by = [ '-nid' ])

  

reverse(self):spa

1
2
3
# 倒序
       models.UserInfo.objects. all ().order_by( '-nid' ).reverse()
       # 注:若是存在order_by,reverse則是倒序,若是多個排序則一一倒序

  下面兩個 取到的是對象,而且注意 取到的對象能夠 獲取其餘字段(這樣會再去查找該字段下降性能
defer(self, *fields):code

1
2
3
4
models.UserInfo.objects.defer( 'username' , 'id' )
       
        models.UserInfo.objects. filter (...).defer( 'username' , 'id' )
        # 映射中排除某列數據

  

only(self, *fields):

1
2
3
4
# 僅取某個表中的數據
       models.UserInfo.objects.only( 'username' , 'id' )
      
       models.UserInfo.objects. filter (...).only( 'username' , 'id' )
相關文章
相關標籤/搜索