使用django-model-utils自动下载到子类 [英] Automatically downcast to subclass using django-model-utils
问题描述
我有多个用户模型..所有继承使用自定义管理器的基本模型
I have multiple user models .. all inheriting a Base model with a custom manager
class BaseUser(models.Model):
[...]
objects = UserManager()
class StaffUser(BaseUser):
[...]
class Customer(BaseUser):
[...]
managers.py
managers.py
from model_utils.managers import InheritanceManager
class UserManager(..., InheritanceManager):
[...]
通过从django-model-utils继承InheritanceManager,我可以对继承的模型进行自动下载。所以例如,如果我有3个对象,每个用户类型之一:
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]
为此,我必须明确地调用 .select_subclasses()
,
To do that, I had to explicitly call .select_subclasses()
,
但是我想自动进行下载,而无需调用 .select_subclasses()
But I want to do the downcasting automatically without having to call .select_subclasses()
所以我试过:
class UserManager(...,InheritanceManager):
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()
我得到这个: p>
I get this:
MultipleObjectsReturned: get() returned more than one BaseUser -- it returned 3!
是否可以使用django-model-utils对继承的模型进行自动下载?
Is it possible to do automatic downcasting for inherited models using django-model-utils?
推荐答案
我想出来了!
from model_utils.managers import InheritanceQuerySet
class UserManager([...]):
def get_queryset(self):
return InheritanceQuerySet(self.model).select_subclasses()
我没有继承 InheritanceManager
,而是使用 InheritanceQuerySet
。
I didn't have to inherit InheritanceManager
, instead use the InheritanceQuerySet
.
这篇关于使用django-model-utils自动下载到子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!