Django-contenttypes - List all common relationships for a model

I would like to think about the model and list all its inverse general relationships.

My model looks like this:

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

    statuses = generic.GenericRelation(Status)

The Status object is as follows:

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

    class Meta:
        verbose_name_plural = 'statuses'

I would like to programmatically find out what statusesis the general relation for the Service model. Is it possible? Status._meta.fieldsdoesn't show statuses, but Status._meta.get_all_field_names()does, it only shows other unwanted things.

I thought this might be a possible solution, but to me it seems very dirty. I would like to hear about the best.

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)

Thank!

+3
source share
1 answer

GenericRelationworks the same way ManyToManyField. You can find it in Service._meta.many_to_many:

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

All Articles