开发者

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

This question already has answers here: Closed 10 years ago.

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 inherit开发者_如何学运维s 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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜