Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
550 views
in Technique[技术] by (71.8m points)

view - How to show related items using DeleteView in Django?

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...