【问题标题】:Automatically downcast to subclass using django-model-utils使用 django-model-utils 自动向下转换为子类
【发布时间】:2014-09-25 17:36:50
【问题描述】:

我有多个用户模型 .. 都继承了带有自定义管理器的 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 对继承的模型进行自动向下转换?

【问题讨论】:

    标签: python django django-models multiple-inheritance


    【解决方案1】:

    我想通了!

    managers.py

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

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

    【讨论】:

      猜你喜欢
      • 2021-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-23
      • 1970-01-01
      • 1970-01-01
      • 2014-10-01
      • 2021-11-23
      相关资源
      最近更新 更多