Last active
July 22, 2019 07:57
-
-
Save ragecryx/c2e9ad50d921bc2dbf26d321de6cf09c to your computer and use it in GitHub Desktop.
AntDesign Table x Django-Filters -- Ascend/Descend parameters support
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class AntCompatibleOrderingFilter(filters.OrderingFilter): | |
def __init__(self, *args, **kwargs): | |
super(AntCompatibleOrderingFilter, self).__init__(*args, **kwargs) | |
def build_choices(self, fields, labels): | |
""" | |
Adds support for {field}-ascend and {field}-descend choices | |
""" | |
ascending = [ | |
(f"{param}-ascend", labels.get(field, _(pretty_name(param)))) | |
for field, param in fields.items() | |
] | |
descending = [ | |
(f"{param}-descend", labels.get(f"{param}-descend", self.descending_fmt % param)) | |
for field, param in fields.items() | |
] | |
# interleave the ascending and descending choices | |
return [val for pair in zip(ascending, descending) for val in pair] | |
def get_ordering_value(self, param): | |
""" | |
Converts {field}-ascend and {field}-descend URL params | |
to Django ORM compatible sorters | |
""" | |
descending = param.endswith('-descend') | |
param_split = param.split('-') | |
if len(param_split) != 2: | |
return param | |
else: | |
field_name = self.param_map.get(param_split[0], param) | |
return "-%s" % field_name if descending else field_name |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment