在django中覆盖UserManager

Thi*_*t J 9 authentication django usermanager

如何auth_user在django中为该类使用自定义管理器?

在我的django项目中,我正在使用auth_user,我有一个基本的个人资料类.在我网站的每个页面中,我都使用了一些用户和个人资料数据,因此每个用户查询都应该加入个人资料.

我想在自定义管理器中使用select_relatedget_query_set()方法,但我找不到任何正确的方法来定义一个,或覆盖现有的UserManager.有任何想法吗?

注意:我不想覆盖用户模型.或者,更确切地说,我已经在不同的代理模型中覆盖了它.我希望在每个代理模型中使用此自定义管理器.

Thi*_*t J 7

好的,终于找到了正确的答案.最干净的方法是使用自定义身份验证后端.

# in settings:
AUTHENTICATION_BACKENDS = ('accounts.backends.AuthenticationBackend',)


# in accounts/backends.py:
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.models import User


class AuthenticationBackend(ModelBackend):
    def get_user(self, user_id):
        try:
            # This is where the magic happens
            return User.objects. \
                select_related('profile'). \
                get(pk=user_id)
        except User.DoesNotExist:
            return None
Run Code Online (Sandbox Code Playgroud)