Code

Ticket #19895: 19895_2.diff

File 19895_2.diff, 1.0 KB (added by gnosek, 14 months ago)
Line 
1diff --git a/django/db/models/query.py b/django/db/models/query.py
2index 0f3a79a..817f518 100644
3--- a/django/db/models/query.py
4+++ b/django/db/models/query.py
5@@ -104,7 +104,7 @@ class QuerySet(object):
6             len(self)
7 
8         if self._result_cache is None:
9-            self._iter = self.iterator()
10+            self._iter = self.safe_iterator(self.iterator())
11             self._result_cache = []
12         if self._iter:
13             return self._result_iter()
14@@ -341,6 +341,18 @@ class QuerySet(object):
15 
16             yield obj
17 
18+    def safe_iterator(self, iterator):
19+        # ensure result cache is cleared when iterating over a queryset
20+        # raises an exception
21+        try:
22+            for item in iterator:
23+                yield item
24+        except StopIteration:
25+            raise
26+        except Exception:
27+            self._result_cache = None
28+            raise
29+
30     def aggregate(self, *args, **kwargs):
31         """
32         Returns a dictionary containing the calculations (aggregation)