django - 在 Django View 中检索和使用 ContentType 的最佳实践

标签 django performance contenttypes

一个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/

相关文章:

django - 如何检查 mod_wsgi 是否安装在共享的 Apache 服务器上?

c++ - 与 2,3 和更多整数的子集和相关的想法

javascript - 如何在不执行 JS 文件的情况下执行 Jquery.get?

orchardcms - Orchard CMS - 使用字段扩展用户 - 在博客文章中公开值

django - 已应用迁移但没有迁移文件夹

javascript - Django 管理员预填充字段不是错误 "d.Keyup is not a function"

javascript - 如何正确设置附加到按钮的日期选择器

mysql - 在 MySQL 中使用 NULL-able 字段的性能影响

performance - 何时在我的tal :condition?上使用nocall