DeleteView наследует DeletionMixin .Что вы можете сделать, это добавить on_delete=PROTECTED
в вашу дочернюю модель и переопределить метод удаления в вашем представлении, чтобы перехватить исключение ProtectedError
.Информацию об этом сообщении см. В фреймворке сообщений Django .
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)