I have some Django models, say
class Foo(models.Model):
class Meta:
abstract = True
class Bar(Foo)
pass
I would like to be able to find all models inheriting from Foo, in order to perform a task with them. It should be easy, like
from django.db import models
from myapp.models import Foo
for model in models.get_models():
if issubclass(model, Foo):
do_something()
Alas, this does not work, since issubclass(Bar, Foo)
reports False
, probably as a result of the inner working of the Django metaclass that initializes the models.
Is there a way to check whether a Django models is a descendant of an abstract Django model?
Please, do not suggest duck typing as the solution. In this case, I really would like to know whether a subclass relation exists.
The problem is how you import the classes. Instead of:
from myapp.models import Foo
use:
from myproject.myapp.models import Foo
To see what is the right way, you can see how Django is importing your models with:
print models.get_models()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With