[Solved]-Iterating over a Django QuerySet while deleting objects in the same QuerySet

7👍

So I guess I have answered my own question by asking it, if anyone else is curious. I thought there would have been a problem when deleting objects while iterating over them, but there isn’t. The code snippet in the question is the right way to do it.

1👍

Querysets have a delete method that will delete all the results of that queryset. For the example you gave

toarchive.filter(date__gt=interval).delete()

will work. If you’re doing a test that can’t be done in a filter, however, the method you described is probably best.

👤Will

Leave a comment