我正在做一个视图,从模型中删除(使用Django的通用视图DeleteView)一个实例,但它从其他模型级联并删除实例:
url(r'^person/(?P<pk>\d+)/delete/$', login_required(DeleteView.as_view(model=Person, success_url='/person/', template_name='delete.html')), name='person_delete'),
我想要做的是显示要删除的相关项目列表,如管理界面那样:
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
答案 0 :(得分:39)
您可以使用Django使用的Collector
类来确定要在级联中删除的对象。实例化它,然后在其上调用collect
传递您要删除的对象。它需要一个列表或查询集,所以如果你只有一个对象,只需放入一个列表:
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包有一个名为NestedObjects
的Collector
子类,它的工作方式相同,但是nested
返回分层列表的方法:
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
答案 1 :(得分:8)
更新:来自Django 1.9+ NestedObject应该从django.contrib.admin.util s
导入php artisan migrate:refresh
答案 2 :(得分:2)
我使用来自admin的get_deleted_objects()的缩减修改 并使用它在删除视图中扩展我在get_context中的上下文:
from django.contrib.admin.utils import NestedObjects
from django.utils.text import capfirst
from django.utils.encoding import force_text
def get_deleted_objects(objs):
collector = NestedObjects(using='default')
collector.collect(objs)
#
def format_callback(obj):
opts = obj._meta
no_edit_link = '%s: %s' % (capfirst(opts.verbose_name),
force_text(obj))
return no_edit_link
#
to_delete = collector.nested(format_callback)
protected = [format_callback(obj) for obj in collector.protected]
model_count = {model._meta.verbose_name_plural: len(objs) for model, objs in collector.model_objs.items()}
#
return to_delete, model_count, protected
from somewhere import get_deleted_objects
#
class ExampleDelete(DeleteView):
# ...
def get_context_data(self, **kwargs):
#
context = super().get_context_data(**kwargs)
#
deletable_objects, model_count, protected = get_deleted_objects([self.object])
#
context['deletable_objects']=deletable_objects
context['model_count']=dict(model_count).items()
context['protected']=protected
#
return context
<table>
<tr>
<th>Name</th>
<th>Amount</th>
</tr>
{% for model_name, object_count in model_count %}
<tr>
<td>{{ model_name|capfirst }}</td>
<td>{{ object_count }}</td>
</tr>
{% endfor %}
</table>
<p>
<ul>
{{ deletable_objects|unordered_list }}
</ul>
</p>