Skip to content

Instantly share code, notes, and snippets.

@sainipray
Created February 27, 2020 09:53
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sainipray/750820b6ece1f81e022cbab56e68174c to your computer and use it in GitHub Desktop.
Save sainipray/750820b6ece1f81e022cbab56e68174c to your computer and use it in GitHub Desktop.
Custom Django rest framework Ordering Filter
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
@azhar-iqbal2942
Copy link

Thanks this is exactly what I am looking for.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment