簡體   English   中英

Django:我如何獲得模型繼承的模型? [重復]

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

可能重復:
獲取python類parent(s)

我有一個:

class Animal(models.Model):
    pass

class Cat(Aminal):
    pass

class StreetCat(Cat):
    pass

如何找出模型繼承的模型?

你可以通過__base__獲取python中的直接超類

>>> StreetCat.__base__ is Cat
>>> True

如果您有多個基類class Foo(A, B) __bases__將為您提供所有父類的元組


感謝OP更新:以下django方法不檢索抽象基類,因為從技術上講,這些是用於存儲將每個繼承模型綁定到其父項的外鍵的內部使用方法。 被警告!

Django還間接地為繼承模型提供了一些幫助,這些模型是遍歷超類的純python方法的快捷方式。

>>> StreetCat._meta.get_parent_list() 
[Out] : Set([Class Animal, Class Cat])

InheritedClass.parents是所有父項的有序字典,因此如果您需要,以下內容可用於獲取最高父項:

>>> StreetCat._meta.parents.keys()[-1]

你也可以使用非django相關的方法,比如

>>> 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM