Django 模型继承管理器吗? (我的好像没有)
我有 2 个模型:
class A(Model):
#Some Fields
objects = ClassAManager()
class B(A):
#Some B-specific fields
我希望 B.objects
能够让我访问 ClassAManager
的实例,但事实并非如此......
>>> A.objects
<app.managers.ClassAManager object at 0x103f8f290>
>>> B.objects
<django.db.models.manager.Manager object at 0x103f94790>
为什么不< code>B 继承了 A
的 objects
属性?
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
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的基类需要是一个抽象基类,以便继承自定义管理器,如所述此处
Your base class will need to be an abstract base class in order for the custom manager to be inherited, as described here
从 Django 3.1 开始,自定义管理器是从父抽象基类继承的。然而,有一个非常重要的警告 - 与普通类不同,子类不会有默认的
对象
管理器。您必须在父抽象基类上显式设置它。例如,这不会工作,
您将收到此错误:
现在
Child
类只有 1 个管理器custom_manager
,它成为其默认管理器。如果您希望将objects
作为其默认管理器,那么您必须在父抽象基类上显式声明它。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
You will get this error:
Now the
Child
class only has 1 managercustom_manager
, which becomes its default manager. If you would like to haveobjects
as its default manager then you will have to explicitly declare this on the parent abstract base class.