假设我们有以下带有
GenericForeignKey
的模型
class Comment(models.Model):
customer_visible = models.BooleanField(default=False)
comment = models.TextField()
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
model = GenericForeignKey()
并且在其他模型中的几个地方引用了它:
class Invoice(models.Model):
...
comments = GenericRelation(Comment)
...
class Contract(models.Model):
...
comments = GenericRelation(Comment)
是否可以获得引用 Comment 模型的类型列表?例如
[Contract,Invoice]
在这个例子中?
例如使用反射的 C# 也可以实现类似的功能。
我需要一些在没有参考资料的情况下可以工作的东西,所以
Comment.objects.values('content_type')
不起作用。
您可以使用应用程序的
get_models
功能来做到这一点。这是一个例子:
from django.apps import apps
from django.contrib.contenttypes.fields import GenericRelation
all_models = apps.get_models()
models_with_generic_relation = [
model.__name__ for model in all_models if
any(
isinstance(field, GenericRelation)
for field in model._meta.fields
)
]
print(models_with_generic_relation)
在
models_with_generic_relation
中,您将拥有所有具有 GenericRelation
的模型。