假设有两个模型Parent
和Child
。 Parent
到child
是一对多的关系。
我正在为Parent模型创建DeleteView。在删除之前,我需要检查是否Parent
{具有{1}}。如果没有Children
,则Children
模型被删除像往常一样。但是如果有Parent
,那么我需要向DeleteView确认页面发送错误消息。
如何使用DeleteView实现此目的?
答案 0 :(得分:1)
您可以覆盖delete
方法并使用Django's message framework
from django.contrib import messages
class DeletePArent(DeleteView):
# ...
def delete(self, request, *args, **args):
object = self.get_object()
if object.chidlren.count() > 0:
messages.add_message(request, messages.ERROR, "Can't be deleted, has childern")
return redirect('url-of-your-choice')
return super().delete(request, *args, **kwargs)
答案 1 :(得分:1)
DeleteView继承了DeletionMixin。你可以做的就是添加on_delete=PROTECTED
在您的孩子模型和覆盖delete方法在您的视图赶上ProtectedError
例外。有关错误消息,请参见Django的message framework。
models.py:
class Child():
#...
myParent = models.ForeignKey(Parent, on_delete=PROTECTED)
views.py:
from django.db.models import ProtectedError
#...
class ParentDelete(DeleteView):
#...
def delete(self, request, *args, **kwargs):
"""
Call the delete() method on the fetched object and then redirect to the
success URL. If the object is protected, send an error message.
"""
self.object = self.get_object()
success_url = self.get_success_url()
try:
self.object.delete()
except ProtectedError:
messages.add_message(request, messages.ERROR, 'Can not delete: this parent has a child!')
return # The url of the delete view (or whatever you want)
return HttpResponseRedirect(success_url)