Automatically downcast to subclass using django-model-utils

只愿长相守 提交于 2019-12-25 02:28:56

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!