Iterating over a QuerySet Django when deleting objects in the same QuerySet

I am wondering what is the best way to iterate over a Django QuerySet when deleting objects in Queryset? For example, let's say that you have a table of logs with records at a specific time, and you want to archive them so that no more than 1 record every 5 minutes. I know this may be wrong, but this is what I am going to do:

toarchive = Log.objects.all().order_by("-date") start = toarchive[0].date interval = start - datetime.timedelta(minutes=5) for entry in toarchive[1:]: if entry.date > interval: entry.delete() else: interval = entry.date - datetime.timedelta(minutes=5) 
+7
source share
2 answers

Therefore, I think I answered my question by asking it if anyone else is interested. I thought that there was a problem when deleting objects, iterating over them, but no. This piece of code in the question is the right way to do this.

+3
source

Querysets have a delete method that will delete all the results of this set of queries. For the example you specified

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

will work. However, if you are doing a test that cannot be performed in a filter, the method that you described is probably best.

0
source

All Articles