[Django]-How to use Django Proxy Model given a django model object or queryset

4👍

You just need to assign the model attribute of your queryset

users = User.objects.all()
users.model = MyProxyUser
users.first().say_hello()

Edit: For assigning proxy class to a django model object, try

    user = User.objects.all()
    user.__class__ = MyProxyUser
👤Ramast

0👍

Adding to Ramast’s answer, you can also build a function on your proxy model class to consistently do this for you:

class MyProxyUser(User):
...
    @staticmethod
    def from_user(user: UserManager):
        """ Get a PAUser classed instance from a User object.

        Useful for Signals and other Django defaults that send base User objects.
        """
        user.model = PAUser
        return user
...

Leave a comment