在 Django 模型中,如何防止基于特定字段的删除?

Within a Django Model, how can I prevent a delete based on a particular field?

在下面,我有一个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)

我该怎么做?如果使用 QuerySet 批量删除对象,则覆盖 delete 方法将不起作用。我读过不要使用接收器,但我不确定为什么。

这是我在@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.')

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