
[英]How can I mock the created field of a model that inherits from TimeStampedModel using model_mommy?
[英]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.