linski linski - 4 months ago 32
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 import BaseCommand, CommandError

from jobs.models import Job

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

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

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

for job in jobs:
today =
pub_date =

diff = today - pub_date

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

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


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

from django.utils import timezone

past = - 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.