Skip to content

Commit

Permalink
Fixed OrderingFilter handling of empty values. (#1628)
Browse files Browse the repository at this point in the history
A trailing comma would cause a crash trying to map an empty value to a
field name. Ensure sub-values are filtered for EMPTY_VALUES in
addition to the main filter data.

Closes #1597.

Co-authored-by: munnsmunns <mmunns16@gmail.com>
  • Loading branch information
carltongibson and munnsmunns authored Dec 5, 2023
1 parent b9ded74 commit 39bf174
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 4 deletions.
6 changes: 5 additions & 1 deletion django_filters/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -759,7 +759,11 @@ def filter(self, qs, value):
if value in EMPTY_VALUES:
return qs

ordering = [self.get_ordering_value(param) for param in value]
ordering = [
self.get_ordering_value(param)
for param in value
if param not in EMPTY_VALUES
]
return qs.order_by(*ordering)

@classmethod
Expand Down
33 changes: 30 additions & 3 deletions tests/test_filtering.py
Original file line number Diff line number Diff line change
Expand Up @@ -1976,9 +1976,15 @@ class Meta:
fields = ["username"]

qs = User.objects.all()
f = F({"o": "username"}, queryset=qs)
names = f.qs.values_list("username", flat=True)
self.assertEqual(list(names), ["aaron", "alex", "carl", "jacob"])
tests = [
{"o": "username"},
QueryDict("o=username,"),
]
for data in tests:
with self.subTest(data=data):
f = F(data, queryset=qs)
names = f.qs.values_list("username", flat=True)
self.assertEqual(list(names), ["aaron", "alex", "carl", "jacob"])

def test_ordering_with_select_widget(self):
class F(FilterSet):
Expand All @@ -1993,6 +1999,27 @@ class Meta:
names = f.qs.values_list("username", flat=True)
self.assertEqual(list(names), ["aaron", "alex", "carl", "jacob"])

def test_csv_input(self):
class F(FilterSet):
o = OrderingFilter(widget=forms.Select, fields=("username",),)

class Meta:
model = User
fields = ["username"]

qs = User.objects.all()
tests = [
{"o": ","},
QueryDict("o=%2c"),
QueryDict("o=,"),
]
for data in tests:
with self.subTest(data=data):
f = F(data, queryset=qs)
self.assertIs(True, f.is_valid())
names = f.qs.values_list("username", flat=True)
self.assertEqual(list(names), ['alex', 'jacob', 'aaron', 'carl'])


class MiscFilterSetTests(TestCase):
def setUp(self):
Expand Down

0 comments on commit 39bf174

Please sign in to comment.