将 `issubclass()` 与 Django 模型结合使用
我有一些 Django 模型,比如说
class Foo(models.Model):
class Meta:
abstract = True
class Bar(Foo)
pass
我希望能够找到从 Foo 继承的所有模型,以便用它们执行任务。这应该很容易,就像
from django.db import models
from myapp.models import Foo
for model in models.get_models():
if issubclass(model, Foo):
do_something()
唉,这不起作用,因为 issubclass(Bar, Foo)
报告 False
,可能是 Django 元类内部工作的结果初始化模型。
有没有办法检查 Django 模型是否是抽象 Django 模型的后代?
请不要建议鸭子打字作为解决方案。在这种情况下,我真的很想知道是否存在子类关系。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
问题是如何导入类。而不是:
使用:
要查看什么是正确的方法,您可以使用以下命令查看 Django 如何导入模型:
The problem is how you import the classes. Instead of:
use:
To see what is the right way, you can see how Django is importing your models with:
也许像
maybe something like
用于
获取描述
Foo
和Bar
之间继承链的列表。Use
to get a list describing the inheritance chain between
Foo
andBar
.