How to assign user and user.profile to the request object using a single database query in django?

32 views Asked by At

Django assign user to request in the django.contrib.auth.middleware.py by calling

request.user = SimpleLazyObject(lambda: get_user(request))

The get_user function is in the init.py file which in turns calls another get_user function in the backends.py

def get_user(self, user_id):
        try:
            user = UserModel._default_manager.get(pk=user_id)
        except UserModel.DoesNotExist:
            return None
        return user if self.user_can_authenticate(user) else None

Here it is making a database call to get user by id. How can I get the user profile(related to user by a one to one field) in the same query and propagate it back so I can assign it to request.profile?

1

There are 1 answers

0
Ali Kargar On

Let's use select_related() to join tables and get both profile and user in a single query, for example:

def get_user(self, user_id):
    profile = Profile.objects.filter(user_id=user_id).select_related("user").first()
    if not profile:
        return None
    return profile if self.user_can_authenticate(user) else None