Reputation: 131
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')
Upvotes: 0
Views: 950
Reputation: 73460
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.
Upvotes: 1
Reputation: 15926
Try this to figure out what went wrong:
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):
jobs = Job.objects.filter(has_paid=True)
for job in jobs:
today = datetime.today().date()
pub_date = job.date_published.date()
diff = today - pub_date
if diff.days >= 30:
job.delete()
# success message
self.stdout.write('Successfully removed all old jobs')
Upvotes: 1