如何在 Django 中使用 DeleteView 显示相关项目? [英] How to show related items using DeleteView in Django?
问题描述
我正在执行一个视图以从模型中删除(使用来自 Django 的通用视图 DeleteView)一个实例,但它会级联并从其他模型中删除实例:
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
推荐答案
您可以使用 Collector
类 Django 使用该类来确定要在级联中删除哪些对象.实例化它,然后调用 collect
传递你打算删除的对象.它需要一个列表或查询集,所以如果你只有一个对象,只需放入一个列表中:
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
返回一个生成器,因此您只能在循环上下文中使用它.如果您更喜欢可以操作的实际数据结构,admin
contrib 包有一个 Collector
子类,称为 NestedObjects
,工作方式相同,但有一个 嵌套
返回分层列表的方法:
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()
更新:自 Django 1.9 起,django.contrib.admin.util 更名为 django.contrib.admin.utils
Updated: Since Django 1.9, django.contrib.admin.util was renamed to django.contrib.admin.utils
这篇关于如何在 Django 中使用 DeleteView 显示相关项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!