使用django-model-utils自动向下转换为子类

时间:2014-08-02 19:10:07

标签: python django django-models multiple-inheritance

我有多个用户模型..都使用自定义管理器继承Base模型

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):
    [...]

通过从django-model-utils继承InheritanceManager,我可以为继承的模型进行自动向下转换。例如,如果我有3个对象,则每个用户类型之一:

user = BaseUser.objects.select_subclasses()

[Customer: customer@example.com, BaseUser: studio@example.com, StaffUser: staff@example.com]

为此,我必须明确地致电.select_subclasses()

但我想自动进行向下转换而无需致电.select_subclasses()

所以我试过了:

类UserManager(...,InheritanceManager):

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

但现在我尝试使用:

user = EmailUser.objects.all()

我明白了:

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

是否可以使用django-model-utils对继承的模型进行自动向下转换?

1 个答案:

答案 0 :(得分:0)

我明白了!

managers.py

from model_utils.managers import InheritanceQuerySet

class UserManager([...]):

    def get_queryset(self):
        return InheritanceQuerySet(self.model).select_subclasses()

我不必继承InheritanceManager,而是使用InheritanceQuerySet