Django ORM 進行查詢操做和性能優化

一, ORM 的基本操做git

 

測試數據django

from django.db import models


class Publisher(models.Model):
  # 出版社
name = models.CharField(max_length=32) addr = models.CharField(max_length=32) phone = models.IntegerField def __str__(self): return self.name

class Author(models.Model):
  # 做者
name = models.CharField(max_length=16) author_detail = models.OneToOneField("AuthorDetail") books = models.ManyToManyField(to="Book") def __str__(self): return self.name class Book(models.Model):
  # 書籍信息
title = models.CharField(max_length=6) price = models.DecimalField(max_digits=5, decimal_places=2) publish_day = models.DateField(auto_now_add=True) publisher = models.ForeignKey(to="Publisher", to_field="id") def __str__(self): return self.title class AuthorDetail(models.Model):
  # 做者詳情
city = models.CharField(max_length=32) email = models.EmailField() def __str__(self): return self.city

 

 

增
 
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()    

 

二, ForeignKey 的使用緣由app

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

extra

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與Q查詢函數

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

    
Book.objects.all().update(price=F("price")+30) 

 

from django.db.models import Q
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)
 
from django.db import connection
cursor = connection.cursor()
cursor.execute("""SELECT * from tb where name = %s""", ['Lennon'])
row = cursor.fetchone()

select_related(self, *fields)性能

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

prefetch_related(self, *lookups)測試

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

annotate(self, *args, **kwargs)(聚合函數)fetch

 from django.db.models import Count, Avg, Max, Min, Sum
 
    v = models.UserInfo.objects.values('u_id').annotate(uid=Count('u_id'))
    # SELECT u_id, COUNT(ui) AS `uid` FROM UserInfo GROUP BY u_id
 
    v = 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
 
    v = 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

 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_
相關文章
相關標籤/搜索