개발 기록

[Django] soft delete (논리 삭제) 구현 본문

Python/Django

[Django] soft delete (논리 삭제) 구현

수염차 2022. 4. 7. 13:23

DRF - ViewSet으로 API를 구성중에 있다

 

class SoftDeleteModel(models.Model):
    is_deleted = models.BooleanField(default=False)

    def delete(self):
        self.is_deleted = True
        self.save()

    def restore(self):
        self.is_deleted = False
        self.save()

    class Meta:
        abstract = True

처음에는 def soft_delete(self): 로 했는데 delete method 보내면 바로 삭제가 되어 적용이 안되었다 ( 내 경우 )

SoftDeleteModel을 생성한 다음 softdelete를 적용할 모델에게 넣어준다

여기 클래스에는 is_delete 컬럼이 없어도 됨

class Post(SoftDeleteModel):
    HOMEWORK = 'HOMEWORK'
    MIRACLE = 'MIRACLE'
    STATUS = [
        (HOMEWORK, _('HOMEWORK')),
        (MIRACLE, _('MIRACLE')),
    ]
    routine_id = models.BigAutoField(primary_key=True)
    account = models.ForeignKey('accounts.User', on_delete=models.CASCADE)

그리고 추가로 views.py에서 리스트 가져올때 is_deleted = False인것만 가져오도록 코드 추가

class RoutineViewSet(ModelViewSet):
    queryset = Post.objects.all()
    serializer_class = PostSerializer
    permission_classes = [IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly]

    def perform_create(self, serializer):
        serializer.save(account_id=self.request.user.id)

    def get_queryset(self):
        user = self.request.user
        if user.is_authenticated:
            return Post.objects.filter(account_id=user.id, is_deleted=False)
        else:
            return Post.objects.none()

 

출처엔 코드가 이것저것 많은데 일단 실행되는 최소한의 코드만 남겨둠

참고한 포스트

https://dev.to/bikramjeetsingh/soft-deletes-in-django-a9j

 

Soft Deletes in Django

What is Soft Deletion? Sometimes, you want to delete something from your database without...

dev.to

https://adriennedomingus.com/blog/soft-deletion-in-django

 

Soft Deletion in Django — Adrienne Domingus

Giving your users the ability to delete objects from your database is a risky proposition — some types of objects are low risk, but others, no matter how much you warn them of the risks of deleting things, will lead to customer requests. You know the kin

adriennedomingus.com

 

Comments