VicenteC
VicenteC

Reputation: 422

How to acces to a model related to a user in DJango

I would like to access to a model related to a user in User. I know that it's possible to get the username or the name of the user using: request.user.get_username() model.py

class Profile(models.Model):

  profile_user   =  models.OneToOneField(User, null=True, on_delete=models.CASCADE)
  profile_note   =  models.CharField(max_length=30,...)

Is there any method to take the related model field without a query? Example: request.user.profile.profile_note

Upvotes: 0

Views: 85

Answers (1)

Iain Shelvington
Iain Shelvington

Reputation: 32244

If you want request.user to always have .profile available without an additional query you can write your own authentication backend that uses select_related when looking up the user so that there is only 1 database query

from django.contrib.auth.backends import ModelBackend
from django.contrib.auth import get_user_model

class ProfileBackend(ModelBackend):
    def get_user(self, user_id):
        UserModel = get_user_model()
        try:
            return UserModel._default_manager.select_related('profile').get(pk=user_id)
        except UserModel.DoesNotExist:
            return None

settings.py

AUTHENTICATION_BACKENDS = [
    'app.backends.ProfileBackend',
]

Now when request.user is loaded from the DB, the profile will be loaded in the same query. You can now access request.user.profile.profile_note without any additional queries

Upvotes: 1

Related Questions