Django:如何让模型继承自? [英] Django: How do I get the model a model inherits from?
问题描述
可能重复:
获取python类父类
我有一个: / p>
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?
推荐答案
您可以在python中获取直接超类, code> __ base __
You can get the direct superclass in python through __base__
>>> StreetCat.__base__ is Cat
>>> True
__基础__
将为您提供一个元组所有的父类,如果你有多个基类 class Foo(A,B)
__bases__
will get you a tuple of all parent classes if you have multiple base classes class Foo(A, B)
更新感谢OP:以下django方法不检索抽象基类,从技术上讲,这些内存使用方法用于存储将每个继承的模型绑定到其父项的外键。警告!
Django还间接为继承的模型提供了一些帮助,这些模型是遍历超类的纯python方法的快捷方式。
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
是所有父母的有序字典,因此如果您想要的话,以下内容可以让父母最多:
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]
您还可以使用非django相关方法,如
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
这篇关于Django:如何让模型继承自?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!