Dynamic Sorting of REST API data using Django Restframework Filters
Dynamic Sorting
Advanced API Ordering with DRF
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():
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:
REST_FRAMEWORK = {
'ORDERING_PARAM': 'sort',
}Now, simplify your view:
from rest_framework.filters import OrderingFilter
class WeatherListView(generics.ListAPIView):
queryset = Weather.objects.all()
filter_backends = (OrderingFilter,)
ordering_fields = ['date', 'city', 'state'] # Optional: Restrict fieldsConclusion
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!
Stay ahead of the curve
Get the latest technical insights on Python, Security, and Cloud Architecture delivered to your inbox.