You can use the Collector
class Django uses to determine what objects to delete in the cascade. Instantiate it and then call collect
on it passing the objects you intend to delete. It expects a list or queryset, so if you only have one object, just put in inside a list:
from django.db.models.deletion import Collector
collector = Collector(using='default') # or specific database
collector.collect([some_instance])
for model, instance in collector.instances_with_model():
# do something
instances_with_model
returns a generator, so you can only use it within the context of a loop. If you'd prefer an actual data structure that you can manipulate, the admin
contrib package has a Collector
subclass called NestedObjects
, that works the same way, but has a nested
method that returns a hierarchical list:
from django.contrib.admin.utils import NestedObjects
collector = NestedObjects(using='default') # or specific database
collector.collect([some_instance])
to_delete = collector.nested()
Updated: Since Django 1.9, django.contrib.admin.util was renamed to django.contrib.admin.utils
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…