Automatically switch to subclass using django-model-utils

I have several custom models .. all inheriting the base model with a custom manager

models.py

class BaseUser(models.Model): [...] objects = UserManager() class StaffUser(BaseUser): [...] class Customer(BaseUser): [...] 

managers.py

 from model_utils.managers import InheritanceManager class UserManager(..., InheritanceManager): [...] 

Inheriting the InheritanceManager from django-model-utils, I can do automatic downcasting for legacy models. For example, if I have 3 objects, one of each type of user:

 user = BaseUser.objects.select_subclasses() [Customer: customer@example.com , BaseUser: studio@example.com , StaffUser: staff@example.com ] 

To do this, I had to explicitly call .select_subclasses() ,

But I want to do downcasting automatically without calling .select_subclasses()

So I tried:

class UserManager (..., InheritanceManager):

  def get_queryset(self, *args, **kwargs): queryset = super(UserManager, self).get_queryset() return queryset.get_subclass(*args, **kwargs) 

But now when I try to use:

 user = EmailUser.objects.all() 

I get this:

 MultipleObjectsReturned: get() returned more than one BaseUser -- it returned 3! 

Is automatic downcasting possible for legacy models using django-model-utils?

0
source share
1 answer

I get it!

managers.py

 from model_utils.managers import InheritanceQuerySet class UserManager([...]): def get_queryset(self): return InheritanceQuerySet(self.model).select_subclasses() 

I do not need to inherit InheritanceManager , use InheritanceQuerySet instead.

0
source

All Articles