Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

[1.5.x] Fixed #19895 -- Made second iteration over invalid queryset r…

…aise an exception too

When iteration over a queryset raised an exception, the result cache
remained initialized with an empty list, so subsequent iterations returned
an empty list instead of raising an exception

Backport of 2cd0eda from master.
  • Loading branch information...
commit d1e87eb3baf75b1b6a0ada46a9b77f7e347cdb60 1 parent 2683e8e
Grzegorz Nosek authored February 23, 2013 jacobian committed February 23, 2013
14  django/db/models/query.py
@@ -102,7 +102,7 @@ def __iter__(self):
102 102
             len(self)
103 103
 
104 104
         if self._result_cache is None:
105  
-            self._iter = self.iterator()
  105
+            self._iter = self._safe_iterator(self.iterator())
106 106
             self._result_cache = []
107 107
         if self._iter:
108 108
             return self._result_iter()
@@ -337,6 +337,18 @@ def iterator(self):
337 337
 
338 338
             yield obj
339 339
 
  340
+    def _safe_iterator(self, iterator):
  341
+        # ensure result cache is cleared when iterating over a queryset
  342
+        # raises an exception
  343
+        try:
  344
+            for item in iterator:
  345
+                yield item
  346
+        except StopIteration:
  347
+            raise
  348
+        except Exception:
  349
+            self._result_cache = None
  350
+            raise
  351
+
340 352
     def aggregate(self, *args, **kwargs):
341 353
         """
342 354
         Returns a dictionary containing the calculations (aggregation)
7  tests/modeltests/basic/tests.py
@@ -2,7 +2,7 @@
2 2
 
3 3
 from datetime import datetime
4 4
 
5  
-from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned
  5
+from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned, FieldError
6 6
 from django.db.models.fields import Field, FieldDoesNotExist
7 7
 from django.test import TestCase, skipIfDBFeature, skipUnlessDBFeature
8 8
 from django.utils import six
@@ -639,3 +639,8 @@ def test_create_relation_with_ugettext_lazy(self):
639 639
         Article.objects.bulk_create([Article(headline=lazy, pub_date=datetime.now())])
640 640
         article = Article.objects.get()
641 641
         self.assertEqual(article.headline, notlazy)
  642
+
  643
+    def test_invalid_qs_list(self):
  644
+        qs = Article.objects.order_by('invalid_column')
  645
+        self.assertRaises(FieldError, list, qs)
  646
+        self.assertRaises(FieldError, list, qs)

0 notes on commit d1e87eb

Please sign in to comment.
Something went wrong with that request. Please try again.