[Fixed]-Casting from base Model instance to derived proxy Model in Django?

8πŸ‘

I think the actual answer to this question should be the comment by @fhahn in the other answer. And by changing class we can avoid the extra database call. Here is sample code:

My proxy model which change the representation from username to email if set:

class MyUser(User):
    class Meta:
        proxy = True
        verbose_name = _('my user')
        verbose_name_plural = _('my users')

    def __str__(self):
        return "%s" % (self.email or self.username)

class Wallet(models.Model):
    owner = models.OneToOneField(MyUser, on_delete=models.PROTECT, related_name='wallet')

    def __str__(self):
        return "%s" % self.owner

A brief test in shell:

>>> from django.contrib.auth.models import User
>>> from my_apps.models import MyUser
>>> user = User.objects.get(pk=4)
>>> user
<User: AbKec6rumI9H9UmAC3Bh2kXUHzj4>
>>> user.email
'john@example.com'
>>> user.wallet
Traceback (most recent call last):
  File "<console>", line 1, in <module>
AttributeError: 'User' object has no attribute 'wallet'
>>> user.__class__ = MyUser
>>> user
<MyUser: john@example.com>
>>> user.wallet
<Wallet: john@example.com>
πŸ‘€John Pang

4πŸ‘

If you really want to have the full proxy object available, this is a quick and dirty solution (at the expense of an extra database call)

class MyUser(User):

    def pretty_username(self): 
        if self.first_name:
            return self.first_name
        return self.username 

    class Meta: 
        proxy = True


def get_myuser(self):
    try:
        return MyUser.objects.get(pk=self.pk)
    except MyUser.DoesNotExist:
        return None

User.add_to_class('get_myuser', get_myuser)

So to use this in a view you could say:

request.user.get_myuser().pretty_username()

Or in a template:

{{ request.user.get_myuser.pretty_username }}

A nicer solution, if you’re not tied to the proxy model idea, would be the following:

def pretty_username(self):
    if self.first_name:
        return self.first_name
    return self.username

User.add_to_class('pretty_username', pretty_username)

This would allow the following:

request.user.pretty_username()

Or

{{ request.user.pretty_username }}
πŸ‘€Evan Brumley

Leave a comment