结合object、Meta和Django型号.Mod

2024-04-24 13:13:35 发布

您现在位置:Python中文网/ 问答频道 /正文

一些新手问,我有这样一个模型:

from django.db import models

class SomeCommons(object):
   # some fields here
   # ...
   class Meta:
      abstract=True

class SomeDjangoModels(SomeCommons,models.Model):
   pass

是否与以下型号相同:

from django.db import models

class SomeModels(models.Model):
   # some fields here
   # ...
   class Meta:
      abstract=True

我知道当这样做时,SomeDjangoModels(SomeCommons,models.Model)来自SomeCommons的属性将在SomeDjangoModels中可用,但问题是如果SomeCommons包含django Meta类,那么Meta类也将在SomeDjangoModels中可用吗?如果是的话,有没有办法证明它(元类确实存在)?

桑克斯


Tags: djangofromimportabstracttruefieldsdbmodel
2条回答

是的,元类是继承的。。。你知道吗

Meta inheritance

When an abstract base class is created, Django makes any Meta inner class you declared in the base class available as an attribute. If a child class does not declare its own Meta class, it will inherit the parent’s Meta. If the child wants to extend the parent’s Meta class, it can subclass it.

但是在您的例子中,它什么也不做,因为在继承子类上abstarct被设置为False。你知道吗

Django does make one adjustment to the Meta class of an abstract base class: before installing the Meta attribute, it sets abstract=False.

Asa结果SomeModels将是抽象的,但SomeDjangoModels不会。你知道吗

不,这两个定义不完全相同。你知道吗

默认情况下,a subclass will inherit its parent's ^{},但它将而不是继承abstract=True属性(因为常见的用例是子类不会是抽象的)。你知道吗

如果您确实希望继承它,那么必须显式重写元类,如文档中所示。(从这个问题看来,您确实希望SomeDjangoModels也是抽象的,但这并不完全清楚。)

如果您确实想要一个具体的(cf meta)子类,那么对于所有实际用途,定义都是相同的。你知道吗

相关问题 更多 >