在下面,我有一个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
方法将无法正常工作。我读过不使用接收器,但我不确定原因。
答案 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.')
我欢迎改进或更好的答案!