StopIteration404 StopIteration404 - 1 month ago 10
Python Question

Django - stop synchronisation between different variables based on filters on same object

Sorry about the confused question, not sure how to describe it properly.

Say that I have a model named

News
, a variable
news
will be used to store the filter results of the un-read
News
with the attribute
read=False
and mark these
news
to
read=True
, then return these
news
to template. The problem is that after update
read=True
, the original variable
news
which should store initial un-read
news
will become empty. What's the methods behind this and how to stop this synchronisation?

Code example:

class News(models.Model):
...
read = models.BooleanField(default=False)

def foo(self):
news = News.object.filter(read=False) # get un-read news correctly
news.update(read=True) # update stored news successfully, but news will become empty

return news # return empty news instead of original filter result


Thanks for your answers.

Answer

Because querysets are lazy. The results aren't evaluated until you actually iterate through the queryset, which in your code presumably happens in the template.

You could convert to a list first:

news_to_read = list(news)
news.update(read=True)
return news_to_read

but be careful if you're using pagination, you're now evaluating the whole set of unread items rather than just one page worth.

Comments