[Fixed]-Auto delete data which is older than 10 days in django


A good way to do this would be to use management command feature in Django Link.

Write your code in python file and put it in cron to run everyday at certain time. In the program look for objects older than 10 days and delete them for your use case.

The reason why you are not getting different days is because you are using character field to store the current date and time in your code. Change the field type of posting_date variable from CharField to DateTimeField. Link

posting_date = models.DateTimeField(auto_now_add=True)

Add a management program. Which would be something like this:

# purge_old_data.py

from django.core.management.base import BaseCommand, CommandError
from cus_leads.models import CustomerLeads 
from datetime import datetime, timedelta

class Command(BaseCommand):
    help = 'Delete objects older than 10 days'

    def handle(self, *args, **options):
        self.stdout.write('Deleted objects older than 10 days')

How to run this command:

python <code_base>/manage.py purge_old_data --settings=<code_base>.settings.<env>

Project structure I am assuming:


However I would recommend you not to delete the objects. Rather add a field as is_deleted and just set that as true after 10 days. This will help you with analytics.

Also @e4c5 pointed out that:

You should delete it or move to an archive table because boolean
columns cannot be indexed effectively and this is going to slow down
your DB over time.


If you are on Unix system use crontab it’s a simple and efficient way to automate tasks, then write a python script (inside your project) that will import your models and do the work for you, using datetime check last X days from today.

Then call it in your crontab like you would call it in the Unix shell.

Hint: you can put a crontab file with all your tasks in your project then copy it or sym link it to /etc/cron.d


Leave a comment