在Django视图中检索和使用ContentType的最佳实践
在oneviews.py的不同视图中检索相同Django内容类型的更有效方法是什么 a)分别检索每个视图中的类型,如下所示:在Django视图中检索和使用ContentType的最佳实践,django,performance,contenttypes,Django,Performance,Contenttypes,在oneviews.py的不同视图中检索相同Django内容类型的更有效方法是什么 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_mode
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
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
或b)在views.py的开头将使用过的类型作为常量检索一次,如下所示:
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
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)因此更快 从注释行到
get_for_model
():
返回给定模型的ContentType对象,必要时创建ContentType。缓存查找,以便同一模型的后续查找不会命中数据库
因此,结果将被缓存,您可以在每个视图中分别检索类型
但是考虑编写一个函数或模型方法,而不是在视图中复制代码的可能性。
假设缓存被保留在视图之外,那将是完美的。所以问题是:这个缓存是全局的,还是像普通的Django查询集一样,仅限于一个视图的运行时?就像问题中的b)选项一样。缓存将在使用同一工作者/服务器进程的任何请求之间共享。例如,如果在Gunicorn下运行Django并启动9个worker,那么每个worker都将有自己的ContentType缓存。