Python Django 使用 get_user_model 与 settings.AUTH_USER_MODEL
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24629705/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Django using get_user_model vs settings.AUTH_USER_MODEL
提问by Prometheus
Reading the Django Documentation:
阅读 Django 文档:
get_user_model()
get_user_model()
Instead of referring to User directly, you should reference the user model using django.contrib.auth.get_user_model(). This method will return the currently active User model – the custom User model if one is specified, or User otherwise.
When you define a foreign key or many-to-many relations to the User model, you should specify the custom model using the AUTH_USER_MODEL setting.
您应该使用 django.contrib.auth.get_user_model() 来引用用户模型,而不是直接引用 User。此方法将返回当前活动的 User 模型 - 如果指定了自定义 User 模型,否则为 User 。
当您为 User 模型定义外键或多对多关系时,您应该使用 AUTH_USER_MODEL 设置指定自定义模型。
I'm confused with the above text. Should I be doing this:
我对上面的文字感到困惑。我应该这样做吗:
author = models.ForeignKey(settings.AUTH_USER_MODEL)
or this...
或这个...
author = models.ForeignKey(get_user_model())
Both seem to work.
两者似乎都有效。
采纳答案by knbk
Using settings.AUTH_USER_MODEL
will delay the retrieval of the actual model class until all apps are loaded. get_user_model
will attempt to retrieve the model class at the moment your app is imported the first time.
使用settings.AUTH_USER_MODEL
将延迟实际模型类的检索,直到所有应用程序都加载完毕。get_user_model
将尝试在第一次导入您的应用程序时检索模型类。
get_user_model
cannot guarantee that the User
model is already loaded into the app cache. It might work in your specific setup, but it is a hit-and-miss scenario. If you change some settings (e.g. the order of INSTALLED_APPS
) it might very well break the import and you will have to spend additional time debugging.
get_user_model
不能保证User
模型已经加载到应用缓存中。它可能适用于您的特定设置,但它是一个偶然的场景。如果您更改某些设置(例如 的顺序INSTALLED_APPS
),很可能会中断导入,您将不得不花费额外的时间进行调试。
settings.AUTH_USER_MODEL
will pass a string as the foreign key model, and if the retrieval of the model class fails at the time this foreign key is imported, the retrieval will be delayed until all model classes are loaded into the cache.
settings.AUTH_USER_MODEL
将传递一个字符串作为外键模型,如果在导入该外键时模型类检索失败,则检索将延迟,直到所有模型类都加载到缓存中。
回答by synw
A way to fallback to the default user model if AUTH_USER_MODEL is not set:
如果未设置 AUTH_USER_MODEL 则回退到默认用户模型的方法:
from django.conf import settings
from django.contrib.auth.models import User
USER_MODEL = getattr(settings, 'AUTH_USER_MODEL', User)
回答by Ilja
New since Django 1.11.
自 Django 1.11 以来的新功能。
Since Django 1.11 you can use get_user_model()
in both cases! So if you don't want to bother about it further, just take it.
从 Django 1.11 开始,您可以get_user_model()
在这两种情况下使用!因此,如果您不想再为它烦恼,请接受它。
"in both cases" means: if you need the user model for accessing its attributes, as well as if you want to define a ForeignKey/ManyToMany-relation.
“在这两种情况下”意味着:如果您需要用户模型来访问其属性,以及您是否想定义一个 ForeignKey/ManyToMany 关系。
From the changelog:
从变更日志:
get_user_model() can now be called at import time, even in modules that define models.
get_user_model() 现在可以在导入时调用,即使在定义模型的模块中也是如此。
so... is there still a reason to use settings.AUTH_USER_MODEL
? Well, the docs still recommend the settings.AUTH_USER_MODEL
(which is a string) for defining relations, but without giving an explicit reason. Might be beneficial for performance, but doesn't seem to matter much.
所以......还有理由使用settings.AUTH_USER_MODEL
吗?好吧,文档仍然推荐settings.AUTH_USER_MODEL
用于定义关系的(这是一个字符串),但没有给出明确的理由。可能对性能有益,但似乎并不重要。
Code example:
代码示例:
from django.db import models
from django.contrib.auth import get_user_model
...
...
user = models.ForeignKey(
get_user_model(),
null=True, # explicitly set null, since it's required in django 2.x. - otherwise migrations will be incompatible later!
...
)
回答by Murey Tasroc
Since Django 1.11, get_user_model()
actually uses settings.AUTH_USER_MODEL
:
从 Django 1.11 开始,get_user_model()
实际使用settings.AUTH_USER_MODEL
:
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)
except ValueError:
raise ImproperlyConfigured("AUTH_USER_MODEL must be of the form 'app_label.model_name'")
except LookupError:
raise ImproperlyConfigured(
"AUTH_USER_MODEL refers to model '%s' that has not been installed" % settings.AUTH_USER_MODEL
)