在一个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)因此更快......?!