首页 > 解决方案 > Django:它如何找到用户模型?

问题描述

AUTH_USER_MODEL在 Django 中有一个问题: https ://docs.djangoproject.com/en/dev/ref/settings/#auth-user-model

默认值为auth.User。但是,实际模型在auth.models.User. Django 如何找到正确的类?

我问是因为当我通常在 Django 中使用模型时,我必须编写from myapp.models import MyModel. 那么,为什么我不需要modelsin auth.Userfor AUTH_USER_MODEL

有人可以解释一下或显示使用它的代码吗?

标签: pythondjango

解决方案


好吧,您models.pyapp. 这意味着您存储模型类的模块app.models. 因此导入内容如下:

from app.models import MyModel

Django 本质上与此无关:这是 Python 从这些模块加载模块和类的方式。

然而,Django 会加载 - 例如,当您运行服务器时 - 位于INSTALLED_APPS设置文件列表中的应用程序(通常是settings.py. app_name.ModelName. 没有理由在models这里指定,因为模型是在 中定义的models.py,因此只会引入“噪声”。

您可以使用[Django-doc]获取对模型类的引用apps.get_model

from django.apps import apps

apps.get_model('app_name', 'ModelName')

因此,它会检查已加载模型的寄存器,并返回对模型的引用。

当存在循环引用时,通过字符串进行链接很有用(有时是必需的) 。例如,如果您有两个模型AB, 并A引用 B andB throughA (for example withForeignKey s), then one of the two models is defined first. This means that if you defineA first, it can not refer to theB` 类本身,因为那时它还不存在。在 Django 中,然后通过字符串指定模型。然后,Django 系统将首先加载模型,然后“打结”:通过将字符串替换为对实际模型类的引用来解析引用。


推荐阅读