问题
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.
回答1:
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()
回答2:
maybe something like
subclasses = Foo.__subclasses__()
for subclass in subclasses:
# we need to keep looking for subclasses of the subclasses
subclasses += subclass.__subclasses__()
# sometimes we don't care about abstract classes
concrete_subclasses = filter(lambda c: not c._meta.abstract, subclasses)
回答3:
Use
Bar._meta.get_base_chain(Foo)
to get a list describing the inheritance chain between Foo
and Bar
.
来源:https://stackoverflow.com/questions/7914787/using-issubclass-with-django-models