Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 447
user1630866 Avatar asked May 09 '13 16:05

user1630866


People also ask

How do I remove items from QuerySet?

queryset acts just like a list so you can . pop() items and del() them.

What does QuerySet []> mean?

A QuerySet is a collection of data from a database. A QuerySet is built up as a list of objects. QuerySets makes it easier to get the data you actually need, by allowing you to filter and order the data.

Which can be used to retrieve an object directly instead of a QuerySet?

Retrieving Single Objects from QuerySets We can do this using the get() method. The get() returns the single object directly. Let's see the following example. As we can see in both examples, we get the single object not a queryset of a single object.


1 Answers

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.

like image 180
user1630866 Avatar answered Sep 22 '22 12:09

user1630866