5

I am trying to get a list of all related model class instance that have a Foreign Key relationship, so that I can do something like model._meta.fields..

Here is what I have so far:

for related_object in A._meta.get_all_related_objects():
        related_name = related_object.field.rel.related_name

but I am not sure how to get related model class..

Thanks for your help!

Nilesh
  • 20,521
  • 16
  • 92
  • 148
amstree
  • 537
  • 1
  • 4
  • 12

3 Answers3

3

In the last Django version (1.8), the options object has a property named related_objects; it will return an iterable with all the foreign relations definitions to the model in place. Each such relation can be inspected for properties:

for relation in A._meta.related_objects:
    print(relation.related_model)    # model which has foreign keys to A
    print(relation.field.name)       # name of the foreign key field

The iterable related_objects represents the "reverse" relations (ManyToOneRel, ManyToManyRel) to the A model.

If it's not obvious, is driven by the field definitions rather then the model definitions, meaning that a related model will have as many entries as ForeingKey fields to the A model it has.

Roba
  • 646
  • 4
  • 13
2

This is working in Django version 3.2. You can check it for other versions.

for t in A._meta._relation_tree:
    print(t.model)
Indika Rajapaksha
  • 1,056
  • 1
  • 14
  • 36
1

You can use .model to get the class name

for related_object in A._meta.get_all_related_objects():
    print related_object.model

Maybe this question/answers could be useful for you as well.

Community
  • 1
  • 1
trinchet
  • 6,753
  • 4
  • 37
  • 60
  • 1
    The question was about "get all related model class". This solution returns the instances. Imagine that the tables are empty. This would return no instance. But the related classes exist. – guettli Jun 10 '15 at 07:26
  • Previous comment is confusing. This returns a class, but it returns the wrong class, since `model` will return the current class, whereas `related_model` returns what was asked for (the related model, obviously). – AlanSE Oct 16 '17 at 18:33