Django:获取抽象基类的所有实现 [英] Django: Get all implementations of an Abstract Base Class

查看:132
本文介绍了Django:获取抽象基类的所有实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经定义了一些如下所示的模型:

I have defined some models which look like this:

class ABClass(models.Model):
   #common attributes
   class Meta:
     abstract = True

class ConcreteClass1(ABClass):
   #implementation specific attributes

class ConcreteClass2(ABClass):
   #implementation specific attributes

class ModifiedConcreteClass1(ConcreteClass1):
   #implementation specific attributes

我有一个视图,它接受一个'type'参数,该参数指定要显示的类的类型。如果'type = None',我想显示所有的ABClass后代(在这种情况下是ConcreteClass {1,2},ModifiedConcreteClass1)。我已经戳过文档,似乎找不到一种不需要维护ConcreteClass列表的方法。 ABClass .__子类__()似乎很有希望,但当我打电话给它时,它返回一个空列表。

I have a view which takes a 'type' parameter which specifies the type of class to display. If 'type=None' I want to display all descendents of ABClass (in this case, ConcreteClass{1,2}, ModifiedConcreteClass1). I have poked around the documentation and cannot seem to find a way of doing this which does not require list of ConcreteClasses be maintained. ABClass.__subclasses__() seemed promising but it returns an empty list when I call it.

目前最好的我的策略是在models.py中创建一个CLASS_LIST变量,该变量在运行时使用ABClass的所有后代填充,使用 inspect 方法。有没有办法使用django api?

At present the best strategy I have is to create a CLASS_LIST variable in models.py which is populated with all descendents of ABClass at runtime using inspect methods. Is there a way to do this using the django api?

谢谢

推荐答案

看看这个类似的问题:

如何在不知道子类的名称的情况下访问django中的对象的子类?

我的解决方案基本是这样的:

My solution to that was essentially this:

def get_children(self):
    rel_objs = self._meta.get_all_related_objects()
    return [getattr(self, x.get_accessor_name()) for x in rel_objs if x.model != type(self)]

尽管还有一些其他好的解决方案。你可能真的希望基类的孩子,而不只是孩子类。如果没有,答案可能会成为您解决问题的动力。

Though there are a number of other good solutions there as well. It seems likely that you actually want the children of the base class, and not just the child classes. If not, the answers there may serve as a motivator for your solution.

这篇关于Django:获取抽象基类的所有实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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