0

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).

Cœur
  • 37,241
  • 25
  • 195
  • 267
Ranju R
  • 2,407
  • 21
  • 16

1 Answers1

2

You can start with the _meta options.

[rel.model for rel in MyModel._meta.get_all_related_objects()]
Yuji 'Tomita' Tomita
  • 115,817
  • 29
  • 282
  • 245
  • 1
    It will return [AnotherModel], but not [AnotherModel, Type]. But its ok because we can find foreignkey models in another way by selecting all fields with foreign key and its model. for field in ModelC._meta.fields: if field.get_internal_type() == "ForeignKey": print field.rel.to – Ranju R Sep 03 '14 at 05:51