Possible Duplicate:
get python class parent(s)
I have a:
class Animal(models.Model):
pass
class Cat(Aminal):
pass
class StreetCat(Cat):
pass
How can I find out the model a model inherits from?
You can get the direct superclass in python through __base__
>>> StreetCat.__base__ is Cat
>>> True
__bases__
will get you a tuple of all parent classes if you have multiple base classes class Foo(A, B)
Update thanks to OP: the following django method does not retrieve abstract base classes, as technically these are internal use methods for storing the foreign keys that tie each inherited model to their parents. Be warned!
Django also indirectly provides some helpers for inherited models which are shortcuts for the pure python methods of traversing the superclasses.
>>> StreetCat._meta.get_parent_list()
[Out] : Set([Class Animal, Class Cat])
InheritedClass.parents
is an ordered dictionary of all parents, so the following would work to get the upper most parent if you wanted:
>>> StreetCat._meta.parents.keys()[-1]
You could also use a non django related method, something like
>>> StreetCat.__mro__[-3]
# once you know that BaseModel is an Object, and since all defined models subclass
# the BaseModel, [-3] is the first class that subclasses models.Model
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With