开发者

Do Django Models inherit managers? (Mine seem not to)

开发者 https://www.devze.com 2022-12-23 06:44 出处:网络
I have 2 models: class A(Model): 开发者_开发知识库#Some Fields objects = ClassAManager() class B(A):

I have 2 models:

class A(Model):
    开发者_开发知识库#Some Fields
    objects = ClassAManager()

class B(A):
    #Some B-specific fields

I would expect B.objects to give me access to an instance of ClassAManager, but this is not the case....

>>> A.objects
<app.managers.ClassAManager object at 0x103f8f290>
>>> B.objects
<django.db.models.manager.Manager object at 0x103f94790>

Why doesn't B inherit the objects attribute from A?


Your base class will need to be an abstract base class in order for the custom manager to be inherited, as described here


As of Django 3.1, custom managers are inherited from the parent abstract base class. However there is a very important caveat - Unlike in normal classes, the child classes won't have the default objects manager. You will have to explicity set this on the parent abstract base class.

For example, this won't work

class AbstractBase(Model):
   # child fields come here

   custom_manager = MyCustomManager()

class Child(AbstractBase):
    # child fields come here
    pass

Child.objects.filter(id=1)

You will get this error:

> Traceback (most recent call last):
  File "<console>", line 1, in <module>
AttributeError: type object 'Child' has no attribute 'objects'

Now the Child class only has 1 manager custom_manager, which becomes its default manager. If you would like to have objects as its default manager then you will have to explicitly declare this on the parent abstract base class.

from django.db.models import Manager, Model

class AbstractBase(Model):
   # child fields come here

   objects = Manager()
   custom_manager = MyCustomManager()
0

精彩评论

暂无评论...
验证码 换一张
取 消