Skip to content

Commit 1268b0f

Browse files
Added MultipleChoiceFilter example test. (#1604)
1 parent 5ba87c4 commit 1268b0f

File tree

1 file changed

+20
-4
lines changed

1 file changed

+20
-4
lines changed

tests/test_filtering.py

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1459,6 +1459,7 @@ class Meta:
14591459
f = F({"favorite_books__title": "Rainbow Six"}, queryset=qs)
14601460
self.assertQuerySetEqual(f.qs, ["alex"], lambda o: o.username)
14611461

1462+
# No choices given, so filtering does nothing.
14621463
class F(FilterSet):
14631464
favorite_books__title = MultipleChoiceFilter()
14641465

@@ -1468,10 +1469,25 @@ class Meta:
14681469

14691470
f = F()
14701471
self.assertEqual(len(f.filters["favorite_books__title"].field.choices), 0)
1471-
# f = F({'favorite_books__title': ['1', '3']},
1472-
# queryset=qs)
1473-
# self.assertQuerySetEqual(
1474-
# f.qs, ['aaron', 'alex'], lambda o: o.username)
1472+
1473+
# Specifying choices allows filter to work. (See also AllValues variants.)
1474+
class F(FilterSet):
1475+
favorite_books__title = MultipleChoiceFilter(
1476+
choices=[
1477+
(b.title, b.title) for b in Book.objects.all()
1478+
]
1479+
)
1480+
1481+
class Meta:
1482+
model = User
1483+
fields = ["favorite_books__title"]
1484+
1485+
f = F({'favorite_books__title': ["Ender's Game", "Snowcrash"]}, queryset=qs)
1486+
self.assertIs(True, f.form.is_valid(), list(f.filters["favorite_books__title"].field.choices))
1487+
self.assertQuerySetEqual(
1488+
f.qs, ['aaron', 'alex'],
1489+
lambda o: o.username,
1490+
)
14751491

14761492
class F(FilterSet):
14771493
favorite_books__title = AllValuesFilter()

0 commit comments

Comments
 (0)