3
在不同視圖中檢索相同Django ContentType的更有效方式在之一 views.py?在Django視圖中檢索和使用ContentTypes的最佳做法
a)分別檢索在每個視圖類型,像這樣:
from django.contrib.contenttypes.models import ContentType
def my_view1(request):
t1 = ContentType.objects.get_for_model(my_model1)
t2 = ContentType.objects.get_for_model(my_model2)
# ... work with t1 and t2
def my_view2(request):
t1 = ContentType.objects.get_for_model(my_model1)
t2 = ContentType.objects.get_for_model(my_model2)
# ... work with t1 and t2
或b)檢索使用的類型一次作爲views.py開頭常量,像這樣:
from django.contrib.contenttypes.models import ContentType
T1 = ContentType.objects.get_for_model(my_model1)
T2 = ContentType.objects.get_for_model(my_model2)
def my_view1(request):
# ... work with T1 and T2
def my_view2(request):
# ... work with T1 and T2
ContentTypes數據庫表非常小,但是,Django仍然需要爲每個查詢建立一個連接。所以我的猜測是,b)因此更快......?!
假設緩存保留在視圖之外,那將是完美的。所以問題是:這個緩存是全局的還是像普通的Django查詢集一樣 - 僅限於一個視圖的運行時? –
這就像你的問題b)選項。緩存將在使用同一個工作/服務器進程的任何請求之間共享。例如,如果您在Gunicorn下運行Django並啓動9個工作人員 - 那麼每個工作人員都將擁有自己的ContentType緩存。 –