简体   繁体   中英

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 ? if it is, is there a way to prove it (the Meta class does exists)?

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. 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.

But in your case it does nothing as absrtact is set to False on the inheriting child class.

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

Asa result SomeModels will be abstract, but SomeDjangoModels will not.

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).

If you do wish to inherit that, you must explicitly override the meta class, as shown in the documentation. (It appears from the question that you do wish SomeDjangoModels to also be abstract, but it's not entirely clear.)

If you do want a concrete (cf meta) subclass, then for all practical purposes the definitions are identical.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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