gpt4 book ai didi

python - Django 使用 get_user_model 与 settings.AUTH_USER_MODEL

转载 作者:IT老高 更新时间:2023-10-28 21:38:39 29 4
gpt4 key购买 nike

阅读 Django 文档:

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.

我对上面的文字感到困惑。我应该这样做吗:

author = models.ForeignKey(settings.AUTH_USER_MODEL)

或者这个……

author = models.ForeignKey(get_user_model())

两者似乎都有效。

最佳答案

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

get_user_model 不能保证 User 模型已经加载到应用缓存中。它可能适用于您的特定设置,但这是一个偶然的情况。如果您更改某些设置(例如 INSTALLED_APPS 的顺序),很可能会破坏导入,您将不得不花费额外的时间进行调试。

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

关于python - Django 使用 get_user_model 与 settings.AUTH_USER_MODEL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24629705/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com