Skip to content

Commit 83c683b

Browse files
committed
Fixed carltongibson#20. When you filter on a multiple choice field for all options itself the same as doing it for no options, which is way more efficient at the DB level.
1 parent dba0f38 commit 83c683b

File tree

3 files changed

+19
-2
lines changed

3 files changed

+19
-2
lines changed

django_filters/filters.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,8 +83,13 @@ class MultipleChoiceFilter(Filter):
8383
field_class = forms.MultipleChoiceField
8484

8585
def filter(self, qs, value):
86+
value = value or ()
87+
# TODO: this is a bit of a hack, but ModelChoiceIterator doesn't have a
88+
# __len__ method
89+
if len(value) == len(list(self.field.choices)):
90+
return qs
8691
q = Q()
87-
for v in (value or ()):
92+
for v in value:
8893
q |= Q(**{self.name: v})
8994
return qs.filter(q).distinct()
9095

django_filters/tests/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
from tests import (GenericViewTests, InheritanceTest, ModelInheritanceTest,
22
DateRangeFilterTest, FilterSetForm, AllValuesFilterTest, InitialValueTest,
3-
RelatedObjectTest, filter_tests)
3+
RelatedObjectTest, MultipleChoiceFilterTest, filter_tests)
44

55
__test__ = {
66
'filter_tests': filter_tests,

django_filters/tests/tests.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,18 @@ class Meta:
133133
self.assertEqual(str(F().form), form_html)
134134

135135

136+
class MultipleChoiceFilterTest(TestCase):
137+
fixtures = ['test_data']
138+
139+
def test_all_choices_selected(self):
140+
class F(django_filters.FilterSet):
141+
class Meta:
142+
model = User
143+
fields = ["status"]
144+
145+
self.assertEqual(list(F({"status": [0, 1]}).qs), list(User.objects.all()))
146+
147+
136148
filter_tests = """
137149
>>> from datetime import datetime
138150
>>> from django import forms

0 commit comments

Comments
 (0)