Django: access the model meta class value
Question:
I have some model classes defined:
class ModelA(models.Model):
class Meta:
abstract = True
class ModelB(ModelA):
class Meta:
abstract = False
So, now I have a class object, I want to check if it is abstract, is there any way to do this?
For example, I want something like:
>>> ModelA.abstract
True
>>> ModelB.abstract
False
Answers:
Oh, I found that it is easy to get the Meta class by _meta
field of the class:
>>> ModelA._meta.abstract
True
technically, strictly speaking, no external method should access a method or property that begins with an underscore (_) as it is private and protected from outsider access. To solve this, in your model file, add a property:
class Foo(models.Model):
class Meta:
verbose_name = "Foolish"
@property
def verbose_name(self):
return self._meta.verbose_name
Then your view can "properly" access the Meta.verbose_name via Foo().verbose_name as opposed to Foo._meta.verbose_name
I have some model classes defined:
class ModelA(models.Model):
class Meta:
abstract = True
class ModelB(ModelA):
class Meta:
abstract = False
So, now I have a class object, I want to check if it is abstract, is there any way to do this?
For example, I want something like:
>>> ModelA.abstract
True
>>> ModelB.abstract
False
Oh, I found that it is easy to get the Meta class by _meta
field of the class:
>>> ModelA._meta.abstract
True
technically, strictly speaking, no external method should access a method or property that begins with an underscore (_) as it is private and protected from outsider access. To solve this, in your model file, add a property:
class Foo(models.Model):
class Meta:
verbose_name = "Foolish"
@property
def verbose_name(self):
return self._meta.verbose_name
Then your view can "properly" access the Meta.verbose_name via Foo().verbose_name as opposed to Foo._meta.verbose_name