从父类获取所有子模型-Django [英] Get all children models from a parent class - Django
问题描述
如何从家长班获得所有孩子的模特儿?
例如,我有:
How can I get all the children models from a parent class? As an example I have :
class Device(PolymorphicModel):
.....
class Mobile(Device):
.....
class Computer(Device):
.....
所以我想从Device模型中获取其所有后代:移动,计算机,而不是实例。
So I want to get from the Device model its all descendants : Mobile, Computer as classes not as instances.
谢谢。
推荐答案
您可以获取 direct 具有 class .__ subclasses__的子类()
[Python-doc] 方法:
You can get the direct subclasses with the class.__subclasses__()
[Python-doc] method:
>>> Device.__subclasses__()
[<class 'Mobile'>, <class 'Computer'>]
但是这些也可能具有子类。我们可以开发一种算法,每次获得下一代算法,并一直这样做直到找到新的子类为止,例如:
It is however possible that these also have subclasses. We can develop an algorithm that each time obtains the next generation, and keeps doing this until no new subclasses are found, like:
def get_descendants(klass):
gen = { klass }
desc = set()
while gen:
gen = { skls for kls in gen for skls in kls.__subclasses__() }
desc.update(gen)
return desc
或带有可变参数数量:
def get_descendants(*klass):
gen = { *klass }
desc = set()
while gen:
gen = { skls for kls in gen for skls in kls.__subclasses__() }
desc.update(gen)
return desc
这将返回包含所有内容的 set()
后代(直接和间接)。
this will return a set()
containing all descendants (both direct and indirect).
这篇关于从父类获取所有子模型-Django的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!