Guirat
Guirat

Reputation: 73

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):
   .....

So I want to get from the Device model its all descendants : Mobile, Computer as classes not as instances.

Thank you.

Upvotes: 5

Views: 1669

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477804

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

or with a variable number of parameters:

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

this will return a set() containing all descendants (both direct and indirect).

Upvotes: 6

Related Questions