问题描述
在下面,我有一个Post
模型. Post
对象具有一个status
字段,该字段可以是'unpublished'
或'published'
.
In the following, I have a Post
model. A Post
object has a status
field that can be 'unpublished'
or 'published'
.
if status is 'published'
,我想防止对象被删除,并希望将此逻辑封装在模型本身中.
if status is 'published'
, I'd like to prevent the object from being deleted, and would like to keep this logic encapsulated in the model itself.
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
方法.我读过不要使用接收器,但是我不确定为什么.
How can I do this? Overriding the delete
method won't work if the objects are being deleted in bulk with a QuerySet
. I've read not to use receivers, but I'm not sure why.
推荐答案
这是我关注@Todor的评论:
This is what I have following @Todor's comment:
在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.')
我欢迎改进或获得更好的答案!
I welcome improvements or better answers!
这篇关于在Django模型中,如何防止基于特定字段的删除?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!