我试图安排一个删除方法,以便cron可以执行它,但我想出CommandError: error job not completed
我填补了一些不知道在哪里:(< / p>
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')
答案 0 :(得分:1)
试着弄明白出了什么问题:
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')
答案 1 :(得分:1)
更快(仅一个数据库查询)和更不容易出错的方法是:
from django.utils import timezone
past = timezone.datetime.today() - timezone.timedelta(days=30)
Job.objects.filter(has_paid=True, date_published__lte=past).delete()
但是,您不应该使用通用except
来处理所有异常。这几乎是never a good idea,它使调试变得更加困难。