pythondjangodjango-modelsrelated-content

Get all models related to this model in django (via ForeignKey, ManyToMany)


I have to get all the models related to my current model. The relations can be by ForeignKey, ManyToManyField or OneToONeField, from this model or to this model.

For eg:

I have a model:

class MyModel(models.Model):
 field = models.Charfield(...)
 type = models.ForeignKey('Type', ...)

class AnotherModel(models.Model):
 label = models.ForeignKey(MyModel, ...)
 ...

class Type(models.Model):
 name = models...
 ...

I need to find related models of the model MyModel, that means if I have a function get_related_models, get_related_models(MyModel) should return [AnotherModel,Type]

Note:The ultimate use of this is I need to invalidate cache of MyModel when ever there is any change in this model and its related models(By using some post_save).


Solution

  • You can start with the _meta options.

    [rel.model for rel in MyModel._meta.get_all_related_objects()]