python - Django 应用程序和 Django 内容类型之间有什么区别?

标签 python django

例如,django apps 和 django contenttype 在获取模型方面有什么区别

from django.apps import apps
model = apps.get_model(app_label=app_label,model_name=model_name)

from django.contrib.contenttypes.models import ContentType
model = ContentType.objects.get(app_label=app_label, model = model).model_class()

最佳答案

apps.get_model(...) 将查找存储在 AppConfig 中与 app_name 相对应的模型。事实上,如果我们看一下 source code [GitHub] ,我们看到:

def get_model(self, app_label, model_name=None, require_ready=True):
    # …
    if require_ready:
        self.check_models_ready()
    else:
        self.check_apps_ready()

    if model_name is None:
        app_label, model_name = app_label.split('.')

    <strong>app_config</strong> = self.get_app_config(app_label)

    if not require_ready and app_config.models is None:
        app_config.import_models()

    return app_config<strong>.get_model(</strong>model_name, require_ready=require_ready<strong>)</strong>

因此首先确定app_label对应的AppConfig,然后调用获取model对象。 AppConfig 有一个列表,其中存储了该 App 的所有模型。然后 get_model(…) logic of the AppConfig is used [GitHub] :

def get_model(self, model_name, require_ready=True):
    # …
    if require_ready:
        self.apps.check_models_ready()
    else:
        self.apps.check_apps_ready()
    try:
        return self.models[model_name.lower()]
    except KeyError:
        raise LookupError(
            "App '%s' doesn't have a '%s' model." % (self.label, model_name))

因此它将在字典中查找模型并返回对该模型对象的引用。


如果您使用ContentType,您实际上首先进行数据库查询以获取相应的ContentType。例如,您可以通过 id 查询 ContentType(这是内容类型的主要目的:将主键映射到模型)。

一旦检索到 ContentType,Django 就知道应用程序的名称和模型的名称。然后它将调用我们之前讨论的 apps.get_model(...),从而检索对正确模型的引用。事实上,.model_class() method is implemented as [GitHub] :

def model_class(self):
    # …
    try:
        return <strong>apps.get_model(</strong>self.app_label, self.model<strong>)</strong>
    except LookupError:
        return None

如果您因此知道应用程序名称和型号名称,那么使用 ContentType 就没有意义了。特别是因为数据库可能会在内容类型上运行落后,从而返回错误的类型。 ContentType 模型通常用于引用数据库中的特定模型。例如通过使用 GenericForeignKey [Django-doc]它由一对两个字段组成:一个 ForeignKey 链接到 ContentType 的项目,另一个包含所引用对象的主键。如果你访问一个模型对象的GenericForeignKey,它会首先获取那个对象的ContentType,然后用记录对象的主键对该模型进行查询.

关于python - Django 应用程序和 Django 内容类型之间有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68967355/

相关文章:

python - 如何使用 Python 3 从不同目录导入模块?

python - 使用psycopg2将django数据库从sqlite迁移到postgres错误

python - 如何在Python中获取发布文件的路径

python - Django FormView 响应

Python-MySQLdb : ValueError - unsupported format - although the use of the execute substitution

c++ - 扫描目录以从 C++ 加载 Python 插件

python - 如果我想在 Ubuntu 上将 Python 2 与 Django 一起使用,如何安装 Python 3

python - Numpy 点积

Javascript - 在元素的 html 中加载模板

python - 值错误: Cannot assign "": "Message.name" must be a "CustomUser" instance