Get all related Django model objects


How can I get a list of all the model objects that have a ForeignKey pointing to an object? (Something like the delete confirmation page in the Django admin before DELETE CASCADE).

I'm trying to come up with a generic way of merging duplicate objects in the database. Basically I want all of the objects that have ForeignKeys points to object "B" to be updated to point to object "A" so I can then delete "B" without losing anything important.

Thanks for your help!

2/10/2010 1:46:12 AM

Accepted Answer

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(): (see reverse in the _get_fields() source also)

3/14/2017 4:33:27 PM

@digitalPBK was close... here is probably what you are looking for using Django's built in stuff

from django.db.models.deletion import Collector
from django.contrib.admin.util import NestedObjects
collector = NestedObjects(using="default") #database name
collector.collect([objective]) #list of objects. single one won't do

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

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow