2016-09-15 78 views
0

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') 

回答

4

你傳入on_delete=models.PROTECT的外鍵ContentType。這僅在刪除內容類型時才起作用,而不是在刪除註釋時起作用。

documentation states

ForeignKey的不同,GenericForeignKey不接受on_delete 參數自定義此行爲;如果需要,您可以簡單地通過不使用GenericRelation來避免 級聯刪除,並且可以通過pre_delete信號提供替代 行爲。

因此模擬的models.PROTECT的行爲,則需要附加pre_delete信號是否存在任何相關評論認爲,拋出一個異常,這樣的事情:

from django.db.models import ProtectedError, signals 

@receiver(signals.pre_delete, Frame) 
def protect_delete(sender, instance, **kwargs): 
    if instance.comments.exists(): 
     raise ProtectedError() 
相關問題