Get all related Django model objects

Give this a try.

class A(models.Model):
    def get_foreign_fields(self):
      return [getattr(self, f.name) for f in self._meta.fields if type(f) == models.fields.related.ForeignKey]

@digitalPBK was close... here is probably what you are looking for using Django's built-in stuff that is used in Django admin for displaying related objects during deletion

from django.contrib.admin.utils import NestedObjects
collector = NestedObjects(using="default") #database name
collector.collect([objective]) #list of objects. single one won't do
print(collector.data)

this allows you to create what the Django admin displays - the related objects to be deleted.


Django <= 1.7

This gives you the property names for all related objects:

links = [rel.get_accessor_name() for rel in a._meta.get_all_related_objects()]

You can then use something like this to get all related objects:

for link in links:
    objects = getattr(a, link).all()
    for object in objects:
        # do something with related object instance

I spent a while trying to figure this out so I could implement a kind of "Observer Pattern" on one of my models. Hope it's helpful.

Django 1.8+

Use _meta.get_fields(): https://docs.djangoproject.com/en/1.10/ref/models/meta/#django.db.models.options.Options.get_fields (see reverse in the _get_fields() source also)


The following is what django uses to get all related objects

from django.db.models.deletion import Collector
collector = Collector(using="default")
collector.collect([a])

print collector.data