django_orm查詢性能優(yōu)化方法
查詢操作和性能優(yōu)化
1.基本操作
增
models.Tb1.objects.create(c1='xx', c2='oo') 增加一條數(shù)據(jù),可以接受字典類型數(shù)據(jù) **kwargs obj = models.Tb1(c1='xx', c2='oo') obj.save()
查
models.Tb1.objects.get(id=123) # 獲取單條數(shù)據(jù),不存在則報(bào)錯(cuò)(不建議) models.Tb1.objects.all() # 獲取全部 models.Tb1.objects.filter(name='seven') # 獲取指定條件的數(shù)據(jù) models.Tb1.objects.exclude(name='seven') # 獲取指定條件的數(shù)據(jù)
刪
models.Tb1.objects.filter(name='seven').delete() # 刪除指定條件的數(shù)據(jù)
改
models.Tb1.objects.filter(name='seven').update(gender='0') # 將指定條件的數(shù)據(jù)更新,均支持 **kwargs obj = models.Tb1.objects.get(id=1) obj.c1 = '111' obj.save() # 修改單條數(shù)據(jù)
2.Foreign key的使用原因
- 約束
- 節(jié)省硬盤
但是多表查詢會(huì)降低速度,大型程序反而不使用外鍵,而是用單表(約束的時(shí)候,通過(guò)代碼判斷)
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查詢
from django.db.models import F models.Tb1.objects.update(num=F('num')+1)
Q查詢
方式一:
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)
# 條件查詢 # 條件可以是:參數(shù),字典,Q
select_related(self, *fields)
性能相關(guān):表之間進(jìn)行join連表操作,一次性獲取關(guān)聯(lián)的數(shù)據(jù)。
model.tb.objects.all().select_related() model.tb.objects.all().select_related('外鍵字段') model.tb.objects.all().select_related('外鍵字段__外鍵字段')
prefetch_related(self, *lookups)
性能相關(guān):多表連表操作時(shí)速度會(huì)慢,使用其執(zhí)行多次SQL查詢 在內(nèi)存中做關(guān)聯(lián),而不會(huì)再做連表查詢
# 第一次 獲取所有用戶表 # 第二次 獲取用戶類型表where id in (用戶表中的查到的所有用戶ID) models.UserInfo.objects.prefetch_related('外鍵字段')
annotate(self, *args, **kwargs)
# 用于實(shí)現(xiàn)聚合group by查詢 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)
# 構(gòu)造額外的查詢條件或者映射,如:子查詢 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):
# 倒序 models.UserInfo.objects.all().order_by('-nid').reverse() # 注:如果存在order_by,reverse則是倒序,如果多個(gè)排序則一一倒序
下面兩個(gè) 取到的是對(duì)象,并且注意 取到的對(duì)象可以 獲取其他字段(這樣會(huì)再去查找該字段降低性能
defer(self, *fields):
models.UserInfo.objects.defer('username','id') 或 models.UserInfo.objects.filter(...).defer('username','id') # 映射中排除某列數(shù)據(jù)
only(self, *fields):
# 僅取某個(gè)表中的數(shù)據(jù) models.UserInfo.objects.only('username','id') 或 models.UserInfo.objects.filter(...).only('username','id')
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家?! ?/p>
相關(guān)文章
Python操作SQLite數(shù)據(jù)庫(kù)的方法詳解
這篇文章主要介紹了Python操作SQLite數(shù)據(jù)庫(kù)的方法,較為詳細(xì)的分析了Python安裝sqlite數(shù)據(jù)庫(kù)模塊及針對(duì)sqlite數(shù)據(jù)庫(kù)的常用操作技巧,需要的朋友可以參考下2017-06-06Python基于pyecharts實(shí)現(xiàn)關(guān)聯(lián)圖繪制
這篇文章主要介紹了Python基于pyecharts實(shí)現(xiàn)關(guān)聯(lián)圖繪制,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-03-03使用Python獲取愛奇藝電視劇彈幕數(shù)據(jù)的示例代碼
這篇文章主要介紹了用Python獲取愛奇藝電視劇彈幕數(shù)據(jù),本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-01-01Python中requirements.txt簡(jiǎn)介(推薦)
Python項(xiàng)目中必須包含一個(gè)?requirements.txt?文件,用于記錄所有依賴包及其精確的版本號(hào),以便新環(huán)境部署,這篇文章主要介紹了Python中requirements.txt簡(jiǎn)介,需要的朋友可以參考下2022-11-11詳解Python的Django框架中inclusion_tag的使用
這篇文章主要介紹了詳解Python的Django框架中inclusion_tag的使用,文中示例基于Python較早的2.x版本,希望能夠注意一下,需要的朋友可以參考下2015-07-07python 基于DDT實(shí)現(xiàn)數(shù)據(jù)驅(qū)動(dòng)測(cè)試
這篇文章主要介紹了python 基于DDT實(shí)現(xiàn)數(shù)據(jù)驅(qū)動(dòng)測(cè)試的方法,幫助大家更好的理解和學(xué)習(xí)使用python,感興趣的朋友可以了解下2021-02-02