在一个views.py中的不同 View 中检索相同的Django ContentTypes的更有效方法是什么?
a) 分别检索每个 View 中的类型,如下所示:
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) 因此更快......?!
最佳答案
从注释行到 get_for_model
( source code ):
Returns the ContentType object for a given model, creating the ContentType if necessary. Lookups are cached so that subsequent lookups for the same model don't hit the database.
因此结果会被缓存,您可以在每个 View 中单独检索类型。
但请考虑编写单个函数或模型方法而不是在 View 中重复代码的可能性。
关于django - 在 Django View 中检索和使用 ContentType 的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18078145/