在Django中覆盖UserManager [英] Override UserManager in django

查看:126
本文介绍了在Django中覆盖UserManager的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Django的auth_user类中使用自定义管理器?

How can I use a custom manager for the auth_user class in django?

在我的django项目中,我使用的是auth_user,并且有一个基本的概要文件类.在网站的每个页面中,我都会使用一些用户和个人资料数据,因此每个用户查询都应加入个人资料.

In my django project, I'm using auth_user and I have a basic profile class. In every page of my site, I use some user and profile data, so every user query should join profile.

我想在自定义管理器的get_query_set()方法中使用select_related,但是我找不到任何合适的方法来定义一个方法或覆盖现有的UserManager.有什么想法吗?

I wanted to use select_related in the get_query_set() method in a custom manager, but I cannot find any proper way to define one, or to override the existing UserManager. Any ideas?

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

Note: I don't want to override the user model. Or, to be more precise, I already overrode it in different proxy models. I want this custom manager to be used in every proxy model.

推荐答案

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

Ok, finally found the correct answer. The cleanest way is to use a custom authentication backend.

# 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

这篇关于在Django中覆盖UserManager的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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