Using `issubclass()` with Django models

时光怂恿深爱的人放手 提交于 2020-05-26 14:29:28

问题


I have some Django models, say

class Foo(models.Model):
    class Meta:
        abstract = True

class Bar(Foo)
    pass

I would like to be able to find all models inheriting from Foo, in order to perform a task with them. It should be easy, like

from django.db import models
from myapp.models import Foo

for model in models.get_models():
    if issubclass(model, Foo):
        do_something()

Alas, this does not work, since issubclass(Bar, Foo) reports False, probably as a result of the inner working of the Django metaclass that initializes the models.

Is there a way to check whether a Django models is a descendant of an abstract Django model?

Please, do not suggest duck typing as the solution. In this case, I really would like to know whether a subclass relation exists.


回答1:


The problem is how you import the classes. Instead of:

from myapp.models import Foo

use:

from myproject.myapp.models import Foo

To see what is the right way, you can see how Django is importing your models with:

print models.get_models()



回答2:


maybe something like

subclasses = Foo.__subclasses__()
for subclass in subclasses:
    # we need to keep looking for subclasses of the subclasses
    subclasses += subclass.__subclasses__()
# sometimes we don't care about abstract classes
concrete_subclasses = filter(lambda c: not c._meta.abstract, subclasses)



回答3:


Use

Bar._meta.get_base_chain(Foo)

to get a list describing the inheritance chain between Foo and Bar.



来源:https://stackoverflow.com/questions/7914787/using-issubclass-with-django-models

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!