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

4

1 回答 1

2

您可以从_meta选项开始。

[rel.model for rel in MyModel._meta.get_all_related_objects()]
于 2014-09-02T19:21:51.813 回答