From 1268b0f83ef5b88e7eda7040ff010b9ec1bbf06e Mon Sep 17 00:00:00 2001 From: Carlton Gibson Date: Sat, 26 Aug 2023 10:10:36 +0200 Subject: [PATCH] Added MultipleChoiceFilter example test. (#1604) --- tests/test_filtering.py | 24 ++++++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/tests/test_filtering.py b/tests/test_filtering.py index 88eca60e..b9b30f9a 100644 --- a/tests/test_filtering.py +++ b/tests/test_filtering.py @@ -1459,6 +1459,7 @@ class Meta: f = F({"favorite_books__title": "Rainbow Six"}, queryset=qs) self.assertQuerySetEqual(f.qs, ["alex"], lambda o: o.username) + # No choices given, so filtering does nothing. class F(FilterSet): favorite_books__title = MultipleChoiceFilter() @@ -1468,10 +1469,25 @@ class Meta: f = F() self.assertEqual(len(f.filters["favorite_books__title"].field.choices), 0) - # f = F({'favorite_books__title': ['1', '3']}, - # queryset=qs) - # self.assertQuerySetEqual( - # f.qs, ['aaron', 'alex'], lambda o: o.username) + + # Specifying choices allows filter to work. (See also AllValues variants.) + class F(FilterSet): + favorite_books__title = MultipleChoiceFilter( + choices=[ + (b.title, b.title) for b in Book.objects.all() + ] + ) + + class Meta: + model = User + fields = ["favorite_books__title"] + + f = F({'favorite_books__title': ["Ender's Game", "Snowcrash"]}, queryset=qs) + self.assertIs(True, f.form.is_valid(), list(f.filters["favorite_books__title"].field.choices)) + self.assertQuerySetEqual( + f.qs, ['aaron', 'alex'], + lambda o: o.username, + ) class F(FilterSet): favorite_books__title = AllValuesFilter()