简体   繁体   English

将对象与Meta和django模型组合

[英]combining object with Meta and django models.Model

some newbie question here, I have a model like so: 这里有一些新手问题,我有一个像这样的模型:

from django.db import models

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

class SomeDjangoModels(SomeCommons,models.Model):
   pass

is it the same as the following model : 与以下模型相同:

from django.db import models

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

What I know that when doing like so SomeDjangoModels(SomeCommons,models.Model) the attribute from SomeCommons will be available in SomeDjangoModels , but the question is if the SomeCommons contains django Meta class will the Meta class also available in SomeDjangoModels ? 我所知道的是,这样做时SomeDjangoModels(SomeCommons,models.Model)SomeCommons属性将在SomeDjangoModels可用,但问题是SomeCommons包含django Meta类, Meta类是否也会在SomeDjangoModels可用? if it is, is there a way to prove it (the Meta class does exists)? 如果是,是否有办法证明它(Meta类确实存在)?

thanx 谢谢

Yes, meta classes are inherited... 是的,元类是继承的...

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. 创建抽象基类后,Django会将您在基类中声明的任何Meta内部类用作属性。 If a child class does not declare its own Meta class, it will inherit the parent's Meta. 如果子类没有声明自己的Meta类,它将继承父类的Meta。 If the child wants to extend the parent's Meta class, it can subclass it. 如果孩子想扩展父母的Meta类,则可以对其进行子类化。

But in your case it does nothing as absrtact is set to False on the inheriting child class. 但是在您的情况下,它没有任何作用,因为在继承的子类上,absrtact设置为False。

Django does make one adjustment to the Meta class of an abstract base class: before installing the Meta attribute, it sets abstract=False . Django确实对抽象基类的Meta类进行了一种调整:在安装Meta属性之前,它会设置abstract=False

Asa result SomeModels will be abstract, but SomeDjangoModels will not. 结果, SomeModels将是抽象的,但SomeDjangoModels将不是抽象的。

No, those two definitions are not quite the same. 不,这两个定义并不完全相同。

By default, a subclass will inherit its parent's Meta , but it will not inherit the abstract=True property (as the common use case is that subclasses will not be abstract). 默认情况下, 子类将继承其父级的Meta ,但不会继承abstract=True属性(因为常见的用例是子类将不是抽象的)。

If you do wish to inherit that, you must explicitly override the meta class, as shown in the documentation. 如果您希望继承该类,则必须显式重写meta类,如文档所示。 (It appears from the question that you do wish SomeDjangoModels to also be abstract, but it's not entirely clear.) (从这个问题看来,您确实希望SomeDjangoModels也可以是抽象的,但是还不完全清楚。)

If you do want a concrete (cf meta) subclass, then for all practical purposes the definitions are identical. 如果确实需要具体的(cf meta)子类,则出于所有实际目的,定义是相同的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM