mercredi 13 septembre 2023

Is there a way to find all models that contain a GenericRelation to a particular model in Django?

Lets say we have the following model with a 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()

And in several places it is referenced in other models:

class Invoice(models.Model):
    ...
    comments = GenericRelation(Comment)
...
class Contract(models.Model):
    ...
    comments = GenericRelation(Comment)

Is it possible to get a list of the types that reference the Comment model? e.g. [Contract,Invoice] in this example?

Similar functionality is possible in for instance C# with Reflection.

I need something that will work when there are no references already, so Comment.objects.values('content_type') won't work.





Aucun commentaire:

Enregistrer un commentaire