How can I use a custom manager for the auth_user
class in django?
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.
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