6

I use a proxy model on User like

class Nuser(User):
    class Meta:
        proxy = True
    def __unicode__(self):
        return u'%s %s' % (self.first_name, self.last_name)

I use it throughout my views.
I was wondering the best way to get the instance of this object for the request.user

Each time I do

Nuser.objects.get(pk=request.user.pk)

Isn't there a simpler way to do it ?

Pierre de LESPINAY
  • 44,700
  • 57
  • 210
  • 307

2 Answers2

14

You could write a custom authentication backend that returns instances of your proxy model instead of a User instance:

from django.contrib.auth.backends import ModelBackend

class ProxiedModelBackend(ModelBackend):
    def get_user(self, user_id):
        try:
            return Nuser.objects.get(pk=user_id)
        except Nuser.DoesNotExist:
            return None

In your settings.py

AUTHENTICATION_BACKENDS = ['my_project.auth_backends.ProxiedModelBackend',]
Benjamin Wohlwend
  • 30,958
  • 11
  • 90
  • 100
-1

There is no way to have Django return, say, a MyNurse object whenever you query for Nurse objects. A queryset for Nurse objects will return those types of objects. The whole point of proxy objects is that code relying on the original Nurse will use those and your own code can use the extensions you included (that no other code is relying on anyway). It is not a way to replace the Nurse (or any other) model everywhere with something of your own creation.

A.J.
  • 8,557
  • 11
  • 61
  • 89