如何防止模型实例删除?

时间:2016-08-05 17:25:50

标签: django python-2.7 django-models django-admin

如果SingleBookis_available_returned,我想使用一种方法来阻止管理员删除False实例。逻辑是,在书籍归还之前,不应删除借书的记录。我宁愿以适当的方式处理它而不是抛出异常。任何帮助将不胜感激。

class SingleBook(models.Model):
    serial_number = models.CharField(primary_key=True , max_length=150, blank=False)
    book_id = models.ForeignKey(LibraryBook, on_delete=models.CASCADE)
    is_available_returned = models.BooleanField(default=True)

    def __unicode__(self):
        return unicode(self.book_id)

PS:

Django==1.9.8
django-material==0.8.0
django-model-utils==2.5.1
psycopg2==2.6.2
wheel==0.24.0

1 个答案:

答案 0 :(得分:1)

from django.core.exceptions import ValidationError
from django.db.models.signals import pre_delete
from django.dispatch import receiver

@receiver(post_save, sender=SingleBook)
def delete_is_available_returned(sender, instance, **kwargs):
    if instance.is_available_returned:
       raise Exception('This book cant be deleted')

在signal中引发异常应该在将异常返回到被调用的位置时强制执行delete()方法执行