Django使用get_user_model与settings.AUTH_USER_MODEL [英] Django using get_user_model vs settings.AUTH_USER_MODEL

查看:549
本文介绍了Django使用get_user_model与settings.AUTH_USER_MODEL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

阅读Django文档:

Reading the Django Documentation:

get_user_model()


应该直接使用django.contrib.auth.get_user_model()来引用用户
模型,而不是直接引用User。此方法将
返回当前活动的用户模型-如果指定了一个
,则返回自定义用户模型,否则返回User。

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.

外键或与用户
模型的多对多关系,应使用AUTH_USER_MODEL
设置指定自定义模型。

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.

我对以上文字感到困惑。我应该这样做吗?

I'm confused with the above text. Should I be doing this:

author = models.ForeignKey(settings.AUTH_USER_MODEL)

或这个...

author = models.ForeignKey(get_user_model())

两者似乎都可以。

推荐答案

使用 settings.AUTH_USER_MODEL 将延迟实际模型类的检索,直到加载所有应用程序为止。 get_user_model 将在您的应用程序首次导入时尝试检索模型类。

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.

get_user_model 无法保证 User 模型已经存在加载到应用缓存中。它可能会在您的特定设置中起作用,但是这是一个命中注定的情况。如果您更改某些设置(例如 INSTALLED_APPS 的顺序),则很可能会中断导入,您将不得不花费更多的时间进行调试。

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.

settings.AUTH_USER_MODEL 将传递一个字符串作为外键模型,如果导入该外键时模型类的检索失败,检索将被延迟,直到所有模型类都加载到缓存中为止。

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.

这篇关于Django使用get_user_model与settings.AUTH_USER_MODEL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆