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

Fix descending choices building for OrderingFilter #1183

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
10 changes: 8 additions & 2 deletions django_filters/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -741,9 +741,15 @@ def build_choices(self, fields, labels):
(param, labels.get(field, _(pretty_name(param))))
for field, param in fields.items()
]

# Descending labels are more complicated:
# - Generated from parameter name
# - Generated from ascending label
# - Provided a descending label
asc = dict(ascending)
descending = [
('-%s' % param, labels.get('-%s' % param, self.descending_fmt % label))
for param, label in ascending
('-%s' % param, labels.get('-%s' % field, self.descending_fmt % asc[param]))
for field, param in fields.items()
]

# interleave the ascending and descending choices
Expand Down
21 changes: 16 additions & 5 deletions tests/test_filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -1508,17 +1508,28 @@ def test_field_labels(self):

def test_field_labels_descending(self):
f = OrderingFilter(
fields=['username'],
fields=(('a', 'b'), ('c', 'd'), ('e', 'f')),
field_labels={
'username': 'BLABLA',
'-username': 'XYZXYZ',
'c': 'BLABLA',
'e': 'BLABLA',
'-e': 'XYZXYZ',
}
)

self.assertEqual(list(f.field.choices), [
('', '---------'),
('username', 'BLABLA'),
('-username', 'XYZXYZ'),

# Generates from prettified asc param name
('b', 'B'),
('-b', 'B (descending)'),

# Generates from provided asc label
('d', 'BLABLA'),
('-d', 'BLABLA (descending)'),

# Given desc label supersedes generated label
('f', 'BLABLA'),
('-f', 'XYZXYZ'),
])

def test_normalize_fields(self):
Expand Down