diff --git a/django_filters/filterset.py b/django_filters/filterset.py index a594a1229..53d48b28e 100644 --- a/django_filters/filterset.py +++ b/django_filters/filterset.py @@ -22,6 +22,7 @@ DateTimeFilter, DurationFilter, Filter, + LookupChoiceFilter, ModelChoiceFilter, ModelMultipleChoiceFilter, NumberFilter, @@ -344,8 +345,11 @@ def get_filters(cls): if field is not None: filters[filter_name] = cls.filter_for_field(field, field_name, lookup_expr) - # filter out declared filters - undefined = [f for f in undefined if f not in cls.declared_filters] + # filter out declared filters where expressions are same as those in declared fields + undefined = [f for f in undefined + if f not in cls.declared_filters or + (not isinstance(cls.declared_filters[f], LookupChoiceFilter) and + fields[f] != [cls.declared_filters[f].lookup_expr])] # noqa if undefined: raise TypeError( "'Meta.fields' contains fields that are not defined on this FilterSet: " diff --git a/tests/test_filtering.py b/tests/test_filtering.py index 538a682ed..1bdd0f52d 100644 --- a/tests/test_filtering.py +++ b/tests/test_filtering.py @@ -1961,3 +1961,21 @@ class Meta: f = F({'status': '2'}, queryset=qs) self.assertEqual(len(f.qs), 2) self.assertEqual(f.qs.count(), 2) + + def test_declared_field_additional_lookup_invalid(self): + msg = "'Meta.fields' contains fields that are not defined on this FilterSet: account" + with self.assertRaises(TypeError) as excinfo: + class F(FilterSet): + account = CharFilter(field_name='username') + + class Meta: + model = User + fields = { + 'account': ['exact', 'contains'], + } + F() + + self.assertEqual( + str(excinfo.exception), + msg + )