问题描述
我试图通过调度程序任务删除过期的收据,但是我遇到一个问题,因为每次运行该函数时,即使有更多对象,它也只能删除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"