2016-07-17 6 views
1

다음은 Post 모델입니다. Post 개체의 필드는 status이고 'unpublished' 또는 'published' 일 수 있습니다.Django 모델에서 특정 필드를 기반으로 삭제를 방지하려면 어떻게해야합니까?

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 메서드를 재정의하는 것은 작동하지 않습니다. 나는 리시버를 사용하지 않겠다는 말을 들었지만 왜 그런지 모르겠습니다.

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.') 

내가 개선 또는 더 나은 답변을 환영

+0

QuerySet.delete()를 통해 삭제할 때 사전 삭제 이벤트가 발생하므로이를 수신하고 ProtectedError를 발생 시키면 트릭을 수행해야합니다. – Todor

+0

문서에서이 파일을 찾을 수 없습니다.이 점을 알려주십시오. 나는 그것이 신호를 보내지 않을 것이라고 생각했다. – StringsOnFire

+0

[pre_delete] (https://docs.djangoproject.com/en/1.9/ref/signals/#pre-delete). 나는 전화로 편지를 쓰고 있는데, 나중에 답을 얻지 못하면 완전한 답을 제공 할 수 없으므로 나중에 답을 제공하려고 노력할 수 있습니다. – Todor

답변

3

이 내가 Todor의 코멘트 @ 다음 한 것입니다!