In my django project I want to auto delete data which is older than 10 days.
How can I write this view? How can it execute automatically?
In my model there is a post_date
field, by which I want to check whether it is 10 days old or not.
model.py:
class CustomerLeads(models.Model):
title = models.CharField(max_length=100, null=True, blank=True)
budget = models.IntegerField(default=0,null=True, blank=True)
posting_date = models.CharField(max_length=300,null=True, blank=True)
quantity = models.IntegerField(default=1,null=True, blank=True)
How can I get diff days. I am getting 2016-12-15 <type 'datetime.date'>
from current date and posting date values I have is 12-Dec-2016 <type 'unicode'>
Thanks in advance.
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):
CustomerLeads.objects.filter(posting_date__lte=datetime.now()-timedelta(days=10)).delete()
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:
cus_leads/
__init__.py
models.py
management/
__init__.py
commands/
__init__.py
purge_old_data.py
tests.py
views.py
-- 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With