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缓存。 –