Created
February 27, 2020 09:53
-
-
Save sainipray/750820b6ece1f81e022cbab56e68174c to your computer and use it in GitHub Desktop.
Custom Django rest framework Ordering Filter
This file contains hidden or 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
from rest_framework.filters import OrderingFilter | |
class CustomOrderFilter(OrderingFilter): | |
allowed_custom_filters = ['user_city', 'user_country'] | |
fields_related = { | |
'user_city': 'user__city__name', # ForeignKey Field lookup for ordering | |
'user_country': 'user__country__name' | |
} | |
def get_ordering(self, request, queryset, view): | |
params = request.query_params.get(self.ordering_param) | |
if params: | |
fields = [param.strip() for param in params.split(',')] | |
ordering = [f for f in fields if f.lstrip('-') in self.allowed_custom_filters] | |
if ordering: | |
return ordering | |
return self.get_default_ordering(view) | |
def filter_queryset(self, request, queryset, view): | |
order_fields = [] | |
ordering = self.get_ordering(request, queryset, view) | |
if ordering: | |
for field in ordering: | |
symbol = "-" if "-" in field else "" | |
order_fields.append(symbol+self.fields_related[field.lstrip('-')]) | |
if order_fields: | |
return queryset.order_by(*order_fields) | |
return queryset |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks this is exactly what I am looking for.