優化場景
利用視圖函數(views)查詢數據之后可以通過上下文context、字典、列表等方式將數據傳遞給HTML模板,由template引擎接收數據并完成解析。但是通過context傳遞數據可能就存在在不同的視圖函數中使用重復的查詢語句,所以可以通過將重復查詢語句設置全局變量,配合locals()函數進行數據查詢與傳遞。
優化前
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
def index(request): threatname = '威脅情報展示' url = 'www.testtip.com' allthreat = Threat.objects. all () #推薦位的威脅情報 rec = Threat.objects. filter (rec__id = 1 )[: 3 ] #情報標簽 threat_tags = Tag.objects. all () #將上述數據封裝至上下文中 context = { 'threatname' : threatname, 'url' : url, 'allthreat' : allthreat, 'rec' :rec, 'threat_tags' :threat_tags, } #通過render傳遞上下文至模板templates return render(request, 'index.html' ,context) def threatshow(request,tid): allthreat = Threat.objects. all () #推薦位的威脅情報 rec = Threat.objects. filter (rec__id = 1 )[: 3 ] #情報標簽 threat_tags = Tag.objects. all () # 熱門情報數據 hot_threat = Threat.objects. filter (hot__id = x)[: 6 ] #將sitename&url&allarticle封裝至上下文中 context = { 'allthreat' : allthreat, 'rec' :rec, 'threat_tags' :threat_tags, 'hot_threat' :hot_threat, } return render(request, 'threatshow.html' ,context) |
上面可以看到 views 里面有 index() 和 threatshow() 兩個視圖函數,在這兩個視圖函數中有三個相同的數據查詢語句:
1
2
3
4
5
|
allthreat = Threat.objects. all () #推薦位的威脅情報 rec = Threat.objects. filter (rec__id = 1 )[: 3 ] #情報標簽 threat_tags = Tag.objects. all () |
優化后
設置全局變量
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
# 全局定義常用查詢數據參數 def global_variable(request): allthreat = Threat.objects. all () #推薦位的威脅情報 rec = Threat.objects. filter (rec__id = 1 )[: 3 ] #情報標簽 threat_tags = Tag.objects. all () return locals () views 中定義上述全局變量后,通過 locals ()函數優化如下: def index(request): threatname = '威脅情報展示' url = 'www.testtip.com' #通過render傳遞上下文至模板templates return render(request, 'index.html' , locals ()) def threatshow(request,tid): # 熱門情報數據 hot_threat = Threat.objects. filter (hot__id = x)[: 6 ] return render(request, 'threatshow.html' , locals ()) |
Python 中的 locals() 函數會以字典類型返回當前位置的全部局部變量,也就是返回當前 index() 、 threatshow() 視圖函數中定義的局部數據查詢結果,加上全局變量當中已經完成了其他剩余數據查詢,所以在滿足數據查詢需求的基礎上完成了視圖函數優化。
到此這篇關于詳解Django中views數據查詢使用locals()函數進行優化的文章就介紹到這了,更多相關Django locals()優化內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://www.cnblogs.com/303donatello/p/13548859.html