linski linski - 13 days ago 7
Python Question

Django management command to delete old objects

I'm trying to schedule a delete method so cron can execute it, but I'm coming up with

CommandError: error job not completed
I stuffed up some where just don't know where :(

from datetime import datetime

from django.core.management.base import BaseCommand, CommandError

from jobs.models import Job

class Command(BaseCommand):
help = 'Deletes the old jobs past 30days'

def handle(self, *args, **options):

try:
jobs = Job.objects.filter(has_paid=True)

for job in jobs:
today = datetime.today()
pub_date = job.date_published.date()

diff = today - pub_date

if diff.days >= 30:
job.delete()
except:
# error message
raise CommandError('error job not completed')

# success message
self.stdout.write('Successfully removed all old jobs')

Answer

A faster (only a single db query) and less error-prone way to do this would be:

from django.utils import timezone

past = timezone.datetime.today() - timezone.timedelta(days=30)
Job.objects.filter(has_paid=True, date_published__lte=past).delete()

Still, you should not use a general except to handle all exceptions. This is almost never a good idea, and it makes debugging that much harder.

Comments