Django管理命令删除旧对象

时间:2016-11-19 21:33:08

标签: python django django-models

我试图安排一个删除方法,以便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')

2 个答案:

答案 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,它使调试变得更加困难。