如何使用django的芹菜拍子任务在所有对象而不是单个对象上工作?

问题描述

我试图通过调度程序任务删除过期的收据,但是我遇到一个问题,因为每次运行该函数时,即使有更多对象,它也只能删除1个对象。当调度程序每60分钟运行一次时,如何更改代码以确保删除所有已过期的对象?

@periodic_task(run_every=crontab(minute='*/60'))
def delete_expired_receipts():
    receipts = Receipt.objects.all()
    for receipt in receipts:
        if receipt.expiry_date <= timezone.Now():
            receipt.delete()
            return "deleted the receipts at {}".format(timezone.Now())
    return "No receipts"

谢谢

解决方法

您需要在循环中删除return语句

@periodic_task(run_every=crontab(minute='*/60'))
def delete_expired_receipts():
    receipts = Receipt.objects.filter(expiry_date__lte=timezone.now())
    if receipts:
       receipts.delete()
       return "Reciepts have been deleted"
    return "No receipts"

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...