在Django中,每当我们想在文件中使用名称为model_name
的模型时,我们都必须将该模型作为导入
from app_name.models import model_name
当我们必须在项目中使用自定义用户模型作为用户模型时,我们必须在设置.py文件中指定对该模型的引用作为
AUTH_USER_MODEL = app_name.model_name
因此,我的问题是,为什么我们必须在设置.py文件中将AUTH_USER_MODEL的值指定为
app_name.model_name
而不是
app_name.models.model_name
为什么我们在设置.py文件中的AUTH_USER_MODEL的值中不使用提及models.py
文件
启动时,django为每个应用程序导入models
模块,并注册所有Model
子类。
django/apps/registry.py
:
# Mapping of app labels => model names => model classes. Every time a
# model is imported, ModelBase.__new__ calls apps.register_model which
# creates an entry in all_models. All imported models are registered,
# regardless of whether they're defined in an installed application
# and whether the registry has been populated. Since it isn't possible
# to reimport a module safely (it could reexecute initialization code)
# all_models is never overridden or reset.
self.all_models = defaultdict(dict)
模型不是由python模块引用的,而是由它们的app_label
和model_name
(小写(引用的。通过app_label
和model_name
来执行对模型的查找。
用户模型不例外:
django/contrib/auth/__init__.py
:
def get_user_model():
"""
Return the User model that is active in this project.
"""
try:
return django_apps.get_model(settings.AUTH_USER_MODEL, require_ready=False)
...
在许多情况下,app_label
也是该应用程序的模块名称,这可能会令人困惑。