访问django中所有抽象基类的子级? [英] Accessing all children of abstract base class in django?

查看:89
本文介绍了访问django中所有抽象基类的子级?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我仍在研究使用抽象基类还是我的控制台应用程序的代理模型。我现在正在看抽象基类。

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)

在控制面板的主页上,我要为我的用户显示所有可用的应用程序。一种简单的方法是获取继承 App 抽象类的所有内容。

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?

推荐答案

假设您的Django应用程序名为 myapp ,这是一个函数,它返回继承了抽象基类的所有类:

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

这在Django 1.11中有效,您必须将其与其他版本配合使用。

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

这篇关于访问django中所有抽象基类的子级?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆