在Django模型中,如何根据特定字段阻止删除?

时间:2016-07-17 09:45:51

标签: django django-models override receiver

在下面,我有一个Post模型。 Post对象的status字段可以是'unpublished''published'

if status is 'published',我想阻止该对象被删除,并希望将此逻辑封装在模型本身中。

from model_utils import Choices  # from Django-Model-Utils
from model_utils.fields import StatusField


class Post(model.Models)

    STATUS = Choices(
        ('unpublished', _('Unpublished')),
        ('published', _('Published')),
    )

    ...

    status = StatusField(default=STATUS.unpublished)

我该怎么做?如果使用delete批量删除对象,则覆盖QuerySet方法将无法正常工作。我读过不使用接收器,但我不确定原因。

1 个答案:

答案 0 :(得分:6)

这就是我跟随@Todor的评论:

signals.py

from django.db.models import ProtectedError
from django.db.models.signals import pre_delete
from django.dispatch import receiver

from .models import Post

@receiver(pre_delete, sender=Post, dispatch_uid='post_pre_delete_signal')
def protect_posts(sender, instance, using, **kwargs):
    if instance.status is 'unpublished': 
        pass
    else:  # Any other status types I add later will also be protected
        raise ProtectedError('Only unpublished posts can be deleted.')

我欢迎改进或更好的答案!