securelms
Engineering
4 min read

Dynamic Sorting of REST API data using Django Restframework Filters

H
Hemachandra Routhu
Project Leader
Published On
July 20, 2022

Please go through my previous post, as this article is a new feature implemented in the same project. We have the Weather model with the following fields: date, latitude, longitude, city, and state.

The Requirement

Initial Manual Approach

We could override get_queryset():

views.py
def get_queryset(self):
    sort_by = self.request.query_params.get('sort', '')
    if sort_by:
        return Weather.objects.all().order_by(sort_by)
    return Weather.objects.all()

The Problem: If there is a slight spelling mistake (e.g., ?sort=date2), the application will raise an error. Handling these errors requires modifying the view repeatedly.

The DRF Way: OrderingFilter

Django Rest Framework gives us OrderingFilter to handle this dynamically. Update your settings.py to change the default parameter name from ordering to sort:

settings.py
REST_FRAMEWORK = {
    'ORDERING_PARAM': 'sort',
}

Now, simplify your view:

views.py
from rest_framework.filters import OrderingFilter

class WeatherListView(generics.ListAPIView):
    queryset = Weather.objects.all()
    filter_backends = (OrderingFilter,)
    ordering_fields = ['date', 'city', 'state'] # Optional: Restrict fields

Conclusion

Like this, we can dynamically sort the records without writing boiler plate code. If a wrong value is provided, it simply returns the default list instead of crashing.

Have a great day!

Spread the Word
Browse More Articles