Skip to content

Commit d1cfec8

Browse files
author
Ryan P Kilby
committed
Fix SearchFilter to-many behavior by ANDing cond's
1 parent f02b7f1 commit d1cfec8

File tree

2 files changed

+7
-1
lines changed

2 files changed

+7
-1
lines changed

rest_framework/filters.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -140,12 +140,14 @@ def filter_queryset(self, request, queryset, view):
140140
]
141141

142142
base = queryset
143+
conditions = []
143144
for search_term in search_terms:
144145
queries = [
145146
models.Q(**{orm_lookup: search_term})
146147
for orm_lookup in orm_lookups
147148
]
148-
queryset = queryset.filter(reduce(operator.or_, queries))
149+
conditions.append(reduce(operator.or_, queries))
150+
queryset = queryset.filter(reduce(operator.and_, conditions))
149151

150152
if self.must_call_distinct(queryset, search_fields):
151153
# Filtering against a many-to-many field requires us to

tests/test_filters.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import warnings
66
from decimal import Decimal
77

8+
import django
89
import pytest
910
from django.conf.urls import url
1011
from django.core.exceptions import ImproperlyConfigured
@@ -668,12 +669,15 @@ def setUpTestData(cls):
668669
b1 = Blog.objects.create(name='Blog 1')
669670
b2 = Blog.objects.create(name='Blog 2')
670671

672+
# Multiple entries on Lennon published in 1979 - distinct should deduplicate
671673
Entry.objects.create(blog=b1, headline='Something about Lennon', pub_date=datetime.date(1979, 1, 1))
672674
Entry.objects.create(blog=b1, headline='Another thing about Lennon', pub_date=datetime.date(1979, 6, 1))
673675

676+
# Entry on Lennon *and* a separate entry in 1979 - should not match
674677
Entry.objects.create(blog=b2, headline='Something unrelated', pub_date=datetime.date(1979, 1, 1))
675678
Entry.objects.create(blog=b2, headline='Retrospective on Lennon', pub_date=datetime.date(1990, 6, 1))
676679

680+
@unittest.skipIf(django.VERSION < (1, 9), "Django 1.8 does not support transforms")
677681
def test_multiple_filter_conditions(self):
678682
class SearchListView(generics.ListAPIView):
679683
queryset = Blog.objects.all()

0 commit comments

Comments
 (0)