Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

[1.0.X] Fixed #10432 -- Handle all kinds of iterators in queryset fil…

…ters.

Only consumes the iterators once and works with Python 2.3.

Backport of r9986 from trunk.

git-svn-id: http://code.djangoproject.com/svn/django/branches/releases/1.0.X@9987 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information...
commit fd5d0cdebbc4e6dd620809c21b97bbb822d60b6d 1 parent 84b890b
Malcolm Tredinnick authored March 08, 2009
4  django/db/models/sql/where.py
@@ -43,6 +43,10 @@ def add(self, data, connector):
43 43
             return
44 44
 
45 45
         alias, col, field, lookup_type, value = data
  46
+        if hasattr(value, '__iter__') and hasattr(value, 'next'):
  47
+            # Consume any generators immediately, so that we can determine
  48
+            # emptiness and transform any non-empty values correctly.
  49
+            value = list(value)
46 50
         try:
47 51
             if field:
48 52
                 params = field.get_db_prep_lookup(lookup_type, value)
24  tests/regressiontests/queries/models.py
@@ -1068,6 +1068,19 @@ def __unicode__(self):
1068 1068
 >>> Tag.objects.filter(name__in=()).update(name="foo")
1069 1069
 0
1070 1070
 
  1071
+Bug #10432 (see also the Python 2.4+ tests for this, below). Testing an empty
  1072
+"__in" filter with a generator as the value.
  1073
+>>> def f():
  1074
+...     return iter([])
  1075
+>>> n_obj = Note.objects.all()[0]
  1076
+>>> def g():
  1077
+...     for i in [n_obj.pk]:
  1078
+...         yield i
  1079
+>>> Note.objects.filter(pk__in=f())
  1080
+[]
  1081
+>>> list(Note.objects.filter(pk__in=g())) == [n_obj]
  1082
+True
  1083
+
1071 1084
 """}
1072 1085
 
1073 1086
 # In Python 2.3 and the Python 2.6 beta releases, exceptions raised in __len__
@@ -1101,3 +1114,14 @@ def __unicode__(self):
1101 1114
 []
1102 1115
 
1103 1116
 """
  1117
+
  1118
+# Generator expressions are only in Python 2.4 and later.
  1119
+if sys.version_info >= (2, 4):
  1120
+    __test__["API_TESTS"] += """
  1121
+Using an empty generator expression as the rvalue for an "__in" lookup is legal
  1122
+(regression for #10432).
  1123
+>>> Note.objects.filter(pk__in=(x for x in ()))
  1124
+[]
  1125
+
  1126
+"""
  1127
+

0 notes on commit fd5d0cd

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