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

I am wondering what is the best way to iterate over a Django QuerySet while deleting objects within the Queryset? For example, say you have a log table with entries at specific times, and you wanted to archive them so that there is no more than 1 entry every 5 minutes. I know this may be wrong, but this is kind of what I am going for:

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)

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.


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.

链接地址: http://www.djcxy.com/p/13342.html

上一篇: 如何通过Indy接收推送通知?

下一篇: 在删除同一个QuerySet中的对象时迭代Django QuerySet