如何使用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
推荐答案
您可以使用 收藏者
类Django用于确定在级联中要删除的对象。实例化它,然后调用收集
,传递您要删除的对象。它期望一个列表或查询器,所以如果你只有一个对象,只需放在一个列表中:
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
子类称为< a href =https://github.com/django/django/blob/master/django/contrib/admin/util.py =noreferrer> 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.util import NestedObjects
collector = NestedObjects(using='default') # or specific database
collector.collect([some_instance])
to_delete = collector.nested()
这篇关于如何使用Django中的DeleteView显示相关项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!