Issue
I have a list of objects I've created using:
plates_under_study = Plate.objects.filter(scan__user=user_focus).filter(scan__date=date_focus).filter(reviewed=False)
After some circumstances, I must set all of these Plate objects reviewed field to True.
I am doing this using the update() method, as in:
plates_under_study.update(reviewed=True)
However, after performing this, I've noticed that my list, plates_under_study
is emptied out. It goes from having a set of objects to [].
This is problematic in that I have other operations I wish to perform through iteration of this list after calling update().
Is there a way to prevent update() from clearing out my list? What is the best way to work around this, other than moving the iterative behavior before calling update() on the list?
Solution
Querysets are lazy. When you call plates_under_study.update(reviewed=True)
, the plates_under_study
queryset hasn't been evaluated yet. When you start iterating after the call to update()
, the queryset shows no items, because there are no unreviewed items at the time the queryset is evaluated.
You need to evaluate the queryset before you update the database. This will cache the results, so iterating them again will yield the items that were unreviewed at the time of the first evaluation:
# Calling bool() will evaluate the queryset and cache the results
bool(plates_under_study)
plates_under_study.update(reviewed=True)
for plate in plates_under_study:
do_something()
Be sure to read "When QuerySets are evaluated".
Answered By - knbk
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.