Automatically delete data older than 10 days in django

In my django project, I want to automatically delete data that is older than 10 days.

How can I write this presentation? How can this be done automatically?

In my model there is a field post_dateaccording to which I want to check whether it has passed 10 days 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 different days. I get 2016-12-15 <type 'datetime.date'>from the current date and publication date values ​​that I have:12-Dec-2016 <type 'unicode'>

Thanks in advance.

+5
source share
2 answers

A good way to do this is to use the command management feature in django Link .

Python cron . 10 .

, datediff , , . posting_date / django. Link

posting_date = models.DateTimeField(auto_now_add=True)

. :

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

:

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

, :

cus_leads/
    __init__.py
    models.py
    management/
        __init__.py
        commands/
            __init__.py
            purge_old_data.py
    tests.py
    views.py

- . is_deleted true 10 . .

@e4c5 , :

, , .

+2

Unix, crontab , python script ( ), , X .

crontab, Unix.

: crontab , sym link it /etc/cron.d

+1

Source: https://habr.com/ru/post/1663836/


All Articles