Using `issubclass ()` with Django Models

I have some Django models, let's say

class Foo(models.Model): class Meta: abstract = True class Bar(Foo) pass 

I would like to find all models that inherit from Foo to do the job with them. It should be easy, for example

 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 , possibly as a result of the internal work of the Django metaclass, which initializes the models.

Is there a way to check if the Django model is a descendant of the abstract Django model?

Please do not offer duck printing as a solution. In this case, I would really like to know if a subclass relation exists.

+6
source share
3 answers

The problem is how to import classes. Instead:

 from myapp.models import Foo 

using:

 from myproject.myapp.models import Foo 

To find out what is the right way, you can see how Django imports your models with:

 print models.get_models() 
+1
source

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) 
0
source

Using

 Bar._meta.get_base_chain(Foo) 

to get a list describing the inheritance chain between Foo and Bar .

0
source

Source: https://habr.com/ru/post/900192/


All Articles