How to show related items using DeleteView in Django?

staticdev picture staticdev · Aug 28, 2012 · Viewed 8.2k times · Source

I am doing a view to delete (using the generic view DeleteView from Django) an instance from a model, but it cascades and deletes instances from other models:

url(r'^person/(?P<pk>\d+)/delete/$', login_required(DeleteView.as_view(model=Person, success_url='/person/', template_name='delete.html')), name='person_delete'),

What I want to do is to show the list of related items that are going to be deleted, as the admin interface does, like:

Are you sure you are going to delete Person NAMEOFTHEPERSON?
By deleting it, you are also going to delete:
CLASSNAME1: CLASSOBJECT1 ; CLASSNAME2: CLASSOBJECT2 ; CLASSNAME3: CLASSOBJECT3 ; etc

Answer

Chris Pratt picture Chris Pratt · Aug 28, 2012

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