python - 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
. 那么,为什么我不需要models
in auth.User
for AUTH_USER_MODEL
?
有人可以解释一下或显示使用它的代码吗?
解决方案
好吧,您models.py
在app
. 这意味着您存储模型类的模块是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')
因此,它会检查已加载模型的寄存器,并返回对模型的引用。
当存在循环引用时,通过字符串进行链接很有用(有时是必需的) 。例如,如果您有两个模型A
和B
, 并A
引用 B and
B through
A (for example with
ForeignKey s), then one of the two models is defined first. This means that if you define
A first, it can not refer to the
B` 类本身,因为那时它还不存在。在 Django 中,然后通过字符串指定模型。然后,Django 系统将首先加载模型,然后“打结”:通过将字符串替换为对实际模型类的引用来解析引用。
推荐阅读
- decision-tree - 根据预期效用选择操作
- javascript - 从统一 webGL 向嵌入它的 vue 页面发送消息
- javascript - 如何编写我自己的车把助手并在 patternlab-node 中使用它?
- c - 二叉搜索树,Valgrind 条件跳转或移动取决于未初始化的值
- visual-studio-code - 如何在视觉工作室代码(mac)中向上/向下移动多行?
- python - 如何选择 NumPy 数组中的所有非黑色像素?
- go - bufio.NewReader.ReadString() 中没有缓冲区大小限制?
- python - 创建窗口后在后台运行代码
- docker - sql developer中的imariadb,自动提交保持“真实”
- laravel - 具有多个房间的酒店预订系统的 Laravel 查询范围编辑方法