Python django contenttypes-列出模型的所有泛型关系

Python django contenttypes-列出模型的所有泛型关系,python,django,django-contenttypes,Python,Django,Django Contenttypes,我想对一个模型进行反思,并列出它的所有向后泛型关系 我的模型如下所示: class Service(models.Model): host = models.ForeignKey(Host) statuses = generic.GenericRelation(Status) class Status(TrackedModel): content_type = models.ForeignKey(ContentType) object_id = models.

我想对一个模型进行反思,并列出它的所有向后泛型关系

我的模型如下所示:

class Service(models.Model):
    host = models.ForeignKey(Host)

    statuses = generic.GenericRelation(Status)
class Status(TrackedModel):
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey()

    class Meta:
        verbose_name_plural = 'statuses'
状态对象如下所示:

class Service(models.Model):
    host = models.ForeignKey(Host)

    statuses = generic.GenericRelation(Status)
class Status(TrackedModel):
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey()

    class Meta:
        verbose_name_plural = 'statuses'
我想通过编程了解
状态
是服务模型的通用关系。这可能吗<代码>状态。_meta.fields不显示
状态,但显示
状态。_meta.get\u all\u field\u names()
显示,只显示其他不需要的内容

我认为这可能是一个可行的解决方案,但对我来说,这似乎真的很混乱。我很想听一个更好的

from django.db.models.fields import FieldDoesNotExist
from django.contrib.contenttypes import generic

generic_relations = []
for field_name in Service._meta.get_all_field_names():
    try:
        field = Service._meta.get_field(field_name)
    except FieldDoesNotExist:
        continue

    if isinstance(field, generic.GenericRelation):
        generic_relations.append(field)

谢谢大家!

generirelation
的工作原理与
ManyToManyField
类似。您可以在
服务中找到它。\u meta.many\u to\u many

filter(lambda f:isinstance(f, generic.GenericRelation), Service._meta.many_to_many)

这是在1.5中使用的,但在1.6中不再使用了。这可能是一个错误,因为我们可以使用
get\u field\u by\u name
获取字段,但不能使用
get\u field
获取字段。遗憾的是,这已经过时了。它似乎只在
服务中可用。_meta.virtual_fields
现在。
virtual_fields
也过时了,至少对于django 2.0来说是这样