djangodjango-viewscelerydjango-celerydjango-celery-beat

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


I am trying to delete the expired receipts through a scheduler task, but I am facing a problem as each time the function runs, it deletes only 1 object even though there are a lot more. How can I change the code I have to make sure that it deletes all the objects which has passed its expiry date, when the scheduler runs every 60 mins?

@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"

Thanks


Solution

  • You need to remove the return statement within the loop

    @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"