본문 바로가기
TTL/13주차 ~ 16주차 TIL (11.21 ~ 12.16)

2022-12-01 TIL (일정기간 지나면 DB 삭제)

by dev_junseok 2022. 12. 4.

인터넷을 이용하는 99%의 사람들이라면, 이런 메일을 본 적이 있을 것이다.

 

'장기 미 이용자 계정 삭제 알림' 이라던가 비슷한 다른 메일을 받아본 적이 있을 것이다.

 

오늘은 해당 기능을 현재 진행하고 있는 팀프로젝트에 적용해보기로 했다.

 

먼저 AbstactBaseUser에는 마지막 로그인 시간이 담기는 Last_login 필드가 자동으로 삽입되어 있다.

 

 

먼저 users앱 안에 Delete_old_user.py 파일을 생성해준다.

from django.core.management.base import BaseCommand, CommandError
from users.models import User
from datetime import datetime, timedelta

class Command(BaseCommand):
    help = '365일보다 오래된 objects를 지운다.'

    def handle(self, *args, **options):
        User.objects.filter(last_login__lte=datetime.now()-timedelta(days=365)).delete()
        self.stdout.write('365일보다 오래된 유저 오브젝트를 제거합니다')

하고 터미널에

python manage.py Delete_old_user.py

를 치면 끝이다.

 

물론 이걸 매일매일 갱신한다는게 좀 귀찮은건 사실이다.

 

이럴때 사용할 수 있는 기능이 crontab 기능이다.

cron - Wikipedia

 

cron - Wikipedia

From Wikipedia, the free encyclopedia Jump to navigation Jump to search Job scheduler for Unix-like operating systems The cron command-line utility is a job scheduler on Unix-like operating systems. Users who set up and maintain software environments use c

en.wikipedia.org

하지만 이 crontab기능은 리눅스, Unix 기반에서만 작동한다. 물론 보통 배포는 우분투에서 진행하기 때문에 문제는 없지만..

 

참조

python - Auto delete data which is older than 10 days in django - Stack Overflow