Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Fixed #2473 -- Added special case for '__in=[]' (empty set) queries, …

…because 'WHERE attr IN ()' is invalid SQL on many backends. Thanks, Gary Wilson.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@4283 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information...
commit ddb9b7d57a1da6b8715a62376cbb8605e6b2351b 1 parent 295f4c9
Russell Keith-Magee authored January 04, 2007
10  django/db/models/query.py
@@ -641,7 +641,15 @@ def get_where_clause(lookup_type, table_prefix, field_name, value):
641 641
     except KeyError:
642 642
         pass
643 643
     if lookup_type == 'in':
644  
-        return '%s%s IN (%s)' % (table_prefix, field_name, ','.join(['%s' for v in value]))
  644
+        in_string = ','.join(['%s' for id in value])
  645
+        if in_string:
  646
+            return '%s%s IN (%s)' % (table_prefix, field_name, in_string)
  647
+        else:
  648
+            # Most backends do not accept an empty string inside the IN
  649
+            # expression, i.e. cannot do "WHERE ... IN ()".  Since there are
  650
+            # also some backends that do not accept "WHERE false", we instead
  651
+            # use an expression that always evaluates to False.
  652
+            return '0=1'
645 653
     elif lookup_type == 'range':
646 654
         return '%s%s BETWEEN %%s AND %%s' % (table_prefix, field_name)
647 655
     elif lookup_type in ('year', 'month', 'day'):
15  tests/modeltests/or_lookups/models.py
@@ -69,6 +69,21 @@ def __str__(self):
69 69
 >>> Article.objects.filter(Q(pk=1) | Q(pk=2) | Q(pk=3))
70 70
 [<Article: Hello>, <Article: Goodbye>, <Article: Hello and goodbye>]
71 71
 
  72
+# You could also use "in" to accomplish the same as above.
  73
+>>> Article.objects.filter(pk__in=[1,2,3])
  74
+[<Article: Hello>, <Article: Goodbye>, <Article: Hello and goodbye>]
  75
+
  76
+>>> Article.objects.filter(pk__in=[1,2,3,4])
  77
+[<Article: Hello>, <Article: Goodbye>, <Article: Hello and goodbye>]
  78
+
  79
+# Passing "in" an empty list returns no results ...
  80
+>>> Article.objects.filter(pk__in=[])
  81
+[]
  82
+
  83
+# ... but can return results if we OR it with another query.
  84
+>>> Article.objects.filter(Q(pk__in=[]) | Q(headline__icontains='goodbye'))
  85
+[<Article: Goodbye>, <Article: Hello and goodbye>]
  86
+
72 87
 # Q arg objects are ANDed
73 88
 >>> Article.objects.filter(Q(headline__startswith='Hello'), Q(headline__contains='bye'))
74 89
 [<Article: Hello and goodbye>]

0 notes on commit ddb9b7d

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