有没有办法在 Django 中查找包含与特定模型的 GenericRelation 的所有模型?

问题描述 投票:0回答:1

假设我们有以下带有

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')
不起作用。

python python-3.x django reflection
1个回答
0
投票

您可以使用应用程序的

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
的模型。

© www.soinside.com 2019 - 2024. All rights reserved.