#Overriding DefaultUserManager

15 messages · Page 1 of 1 (latest)

native solstice
#

So I want to join some tables together for every request, so I thought it makes sense to do that in the user manager since it gets the user on every page too (do it all in one db query). Here's how i added it:

class CustomUserManager(UserManager):
    def get_queryset(self):
        return (
            super()
            .get_queryset()
            .select_related(...)
            .annotate(...)
        )

class User(AbstractUser):
    objects = CustomUserManager()

## settings.py
AUTH_USER_MODEL = "myapp.User"

And yes, this works, but i'm getting two queries now. They're coming from packages that use the default user model, e.g.

  request._cached_user = auth.get_user(request)
\site-packages\django\contrib\auth\__init__.py in get_user(216)
  user = backend.get_user(user_id)
\site-packages\django\contrib\auth\backends.py in get_user(157)
  user = UserModel._default_manager.get(pk=user_id)

How can I make sure the default user model (and UserManager) is properly set everywhere so all INSTALLED_APPS use my new ones? Thanks

modern fossil
#

Why do you think they use default?

#

Generally there should be no case when you default and custom at smae time

native solstice
modern fossil
#

So problem is exactly that you have two queries? How did you monitor queries?

native solstice
#

DjangoToolbar

#

They’re both the exact same query but called in two different spots. One is my custom user and one is the one I listed in the original message

#

Comes with any of the middleware’s I have but only ever gets called in one for some reason. Not sure if that makes any sense

modern fossil
#

One guess is that your method made query a non-lazy one and it's a evaluated before it's time. That is not very solid theory though, but may worth checking

native solstice
#

Hmm maybe, I have no idea how any of it works to be honest

modern fossil
#

If you share what are queries exactly and where they originate maybe it could help too

native solstice
#

Sure thing, I’ll check in the morning - just about to go to bed

modern fossil
#

well, user = UserModel._default_manager.get(pk=user_id) is not lazy from the start so it shouldn't be it

native solstice
#

So that’s forcing a new query?

modern fossil
#

.get() always force a query so question is where the second query comes from and could it be that second can be avoided