如何使用 django 使 celery beat 任务适用于所有对象而不仅仅是单个对象?

How to make celery beat task with django work on all objects rather than just a single object?

我试图通过调度程序任务删除过期的收据,但我遇到了一个问题,因为每次该函数运行时,它只删除 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"