Casting from a base instance of a model to a derived proxy model in Django?

I would like to define a proxy model for the default Django class, something like this:

class MyUser(User): def pretty_username(self): if self.first_name: return self.first_name return self.username class Meta: proxy = True 

And I would like to be able to call pretty_username from the view code (and ideally even from templates). Is there an easy way to take an instance of a standard user model and inject it into an instance of MyUser?

Even __init__ magic would be alright with me if I can say:

 my_user = MyUser(request.user) 

in my view code.

+8
python django django-models
source share
1 answer

If you really want to have full access to the proxy object, this is a quick and dirty solution (due to an additional 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 can say:

 request.user.get_myuser().pretty_username() 

Or in the template:

 {{ request.user.get_myuser.pretty_username }} 

A nicer solution if you are not tied to the idea of ​​a proxy model 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 will do the following:

 request.user.pretty_username() 

or

 {{ request.user.pretty_username }} 
+4
source share

All Articles