Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - how to determine if model class is abstract

If a django model is made abstract, like below, is there a way to inspect the class to determine that it is abstract?

class MyModel(models.Model):
  class Meta:
    abstract = True

I would expect that I could examine MyModel.Meta.abstract, but according to Django docs:

Django does make one adjustment to the Meta class of an abstract base class: before installing the Meta attribute, it sets abstract=False. This means that children of abstract base classes don't automatically become abstract classes themselves.

Any ideas? Thanks!

like image 977
Nagyman Avatar asked Nov 20 '09 19:11

Nagyman


2 Answers

You can instantiate MyModel and then check ._meta.abstract.

So in code:

m = MyModel()
print m._meta.abstract
like image 194
sheats Avatar answered Sep 23 '22 16:09

sheats


I'd like to point out that you don't need to instantiate a model to check if it's abstract - Django models inherit an actual metaclass that adds _meta on class instantiation.

So, similarly to @sheats's code, try

from django.db.models import Model
class MyModel(Model):
  pass
print MyModel._meta.abstract

Or, for a positive example

from django.db.models import Model
class MyModel(Model):
  class Meta(object):
    abstract = True
print MyModel._meta.abstract

Of course, this also works for built-in models and anything inheriting from Django's Model.

from django.contrib.auth.models import User
print User._meta.abstract
like image 34
Matt Luongo Avatar answered Sep 20 '22 16:09

Matt Luongo