About Finding Which Objects Would Be Deleted if You Delete a Certain Instance

The Django administration has a deletion confirmation that lists all related objects that would be deleted if you deleted the current object.

You can also get this list programmatically:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
>>> from pprint import pprint
>>> from django.contrib.admin.utils import NestedObjects
>>> from django.db import DEFAULT_DB_ALIAS
>>> collector = NestedObjects(using=DEFAULT_DB_ALIAS)
>>> collector.collect([director])
>>> pprint(collector.nested())
[<Director: James Cameron>,
 [<Movie: The Terminator>,
 <Movie: Titanic>,
 <Movie: Avatar>]]

Tips and Tricks Programming Development Django 4.2 Django 3.2 Django 2.2 Python 3