Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: How do I get the model a model inherits from? [duplicate]

Tags:

python

django

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?

like image 981
Pickels Avatar asked Mar 11 '11 21:03

Pickels


1 Answers

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
like image 60
Yuji 'Tomita' Tomita Avatar answered Oct 03 '22 15:10

Yuji 'Tomita' Tomita