Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using `issubclass()` with Django models

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.

like image 710
Andrea Avatar asked Oct 27 '11 10:10

Andrea


1 Answers

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()
like image 194
Ivan Ogai Avatar answered Oct 12 '22 03:10

Ivan Ogai