Accessing all children of abstract base class in d

2019-06-07 18:25发布

问题:

I am still researching whether to use abstract base classes or proxy models for my control panel application. I'm looking at the abstract base classes right now.

Assume that I have a few models like this:

class App(models.Model):
    name = CharField(max_length=100)

    class Meta:
        abstract = True

class CMSMonitorApp(App):
    alerts = PositiveIntegerField()

class PasswordResetApp(App):
    login = CharField(max_length=100)
    token = CharField(max_length=100)

On the main page of the control panel, I want to display all of the available applications for my users. An easy way to do this would be to get everything that inherits the App abstract class.

How can I get all of the classes that inherit an abstract base class?

回答1:

Assuming your django application is named myapp, this is a function that returns all of the classes that inherit an abstract base class:

from django.apps import apps
def get_subclasses(abstract_class):
   result = []
   for model in apps.get_app_config('myapp').get_models():
      if issubclass(model, abstract_class) and model is not abstract_class:
           result.append(model)
   return result

This works in django 1.11, you must possibly adapt it with other version.