averageman
averageman

Reputation: 923

Dynamically updated querysets?

I have a model like this:

class M(models.Model):
    ...
    seen = models.BooleanField()
    ...

    def set_seen(self):
        self.seen = True
        self.save()

Then I have this code in a views.py function:

m_not_seen = M.objects.filter(seen=False)
m_seen = M.objects.filter(seen=True)

for m in m_not_seen:
    m.set_seen()

After the last line is executed, it seems like m_seen is updated automatically to include all the entries that were in "not seen" previously. I don't want the queryset to be updated. Is this possible?

Upvotes: 0

Views: 81

Answers (1)

Paolo Bergantino
Paolo Bergantino

Reputation: 488694

Django querysets are lazy, as the documentation says:

Internally, a QuerySet can be constructed, filtered, sliced, and generally passed around without actually hitting the database. No database activity actually occurs until you do something to evaluate the queryset.

In your case, writing m_seen = M.objects.filter(seen=True) does not go to the database until you start looping through it or whatever it is you end up doing with it. At that point, the not seen ones have already been updated to seen.

The documentation goes on to talk about pickling and other ways you can force a QuerySet to be evaluated. In your case, you probably just want to call list() on the QuerySet, just be aware that this will load all the results into memory.

Upvotes: 4

Related Questions