Django

Code

Changeset 4283

Show
Ignore:
Timestamp:
01/03/07 22:00:16 (2 years ago)
Author:
russellm
Message:

Fixed #2473 -- Added special case for 'in=[]' (empty set) queries, because 'WHERE attr IN ()' is invalid SQL on many backends. Thanks, Gary Wilson.

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • django/trunk/django/db/models/query.py

    r4265 r4283  
    642642        pass 
    643643    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' 
    645653    elif lookup_type == 'range': 
    646654        return '%s%s BETWEEN %%s AND %%s' % (table_prefix, field_name) 
  • django/trunk/tests/modeltests/or_lookups/models.py

    r3661 r4283  
    7070[<Article: Hello>, <Article: Goodbye>, <Article: Hello and goodbye>] 
    7171 
     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 
    7287# Q arg objects are ANDed 
    7388>>> Article.objects.filter(Q(headline__startswith='Hello'), Q(headline__contains='bye'))