问题
I have multiple user models .. all inheriting a 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):
[...]
By inheriting the InheritanceManager from django-model-utils, I can do automatic downcasting for inherited models. So for example, if I have 3 objects, one of each user type:
user = BaseUser.objects.select_subclasses()
[Customer: customer@example.com, BaseUser: studio@example.com, StaffUser: staff@example.com]
To do that, I had to explicitly call .select_subclasses()
,
But I want to do the downcasting automatically without having to call .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 it possible to do automatic downcasting for inherited models using django-model-utils?
回答1:
I figured it out!
managers.py
from model_utils.managers import InheritanceQuerySet
class UserManager([...]):
def get_queryset(self):
return InheritanceQuerySet(self.model).select_subclasses()
I didn't have to inherit InheritanceManager
, instead use the InheritanceQuerySet
.
来源:https://stackoverflow.com/questions/25098471/automatically-downcast-to-subclass-using-django-model-utils