Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prevent declared field to have additional lookups #1019

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions django_filters/filterset.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
DateTimeFilter,
DurationFilter,
Filter,
LookupChoiceFilter,
ModelChoiceFilter,
ModelMultipleChoiceFilter,
NumberFilter,
Expand Down Expand Up @@ -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: "
Expand Down
18 changes: 18 additions & 0 deletions tests/test_filtering.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
)