Django的1.10GenericForeignKey和on_delete = models.PROTECT
說,我幀的實例,併爲它的兩條意見。 關鍵時刻:註釋模型中的on_delete = models.PROTECT。
在外殼:
Comment.objects.all()
<QuerySet [<Comment: Some comment.>, <Comment:
Second comment.>]
然後我刪除幀實例(調用FrameDelete)。並且:
Comment.objects.all()
<QuerySet []>
空的。刪除所有評論。而models.PROTECT沒有幫助。
那麼,我不能讓它趕上IntegrityError。你能告訴我,如果可能和如何做?
class FrameDelete(IntegrityErrorMixin, DeleteView):
model = Frame
class IntegrityErrorMixin():
def delete(self, request, *args, **kwargs):
self.object = self.get_object()
success_url = self.get_success_url()
try:
self.object.delete()
except IntegrityError as err:
raise PermissionDenied
return HttpResponseRedirect(success_url)
class Frame(models.Model):
.....
comments = GenericRelation(Comment)
class Comment(models.Model):
date = models.DateTimeField(null=False,
blank=False,
auto_now_add=True)
author = models.ForeignKey(User, on_delete=models.PROTECT)
body = models.TextField(blank=False,
null=False,
default="",
verbose_name = "",) # Empty. No need to show the verbose_name on the form.
content_type = models.ForeignKey(ContentType, on_delete=models.PROTECT)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')