Enhancing Your To-Do API with Sorting

Introduction

Welcome back! So far, we've learned how to enhance our Django-based To-Do API by adding filtering capabilities. You now know how to filter todo items based on both simple and complex criteria, making your API more powerful and user-friendly.

Today, we will focus on adding sorting capabilities to our To-Do API. Sorting is crucial for making APIs more efficient and user-friendly by allowing users to organize data in meaningful ways. By the end of this lesson, you'll be able to sort your To-Do items based on various fields like priority and task name.

Let's get started!

Recap of Previous Setup

In the previous lesson, we set up various filters for our Todo model. Though filters are perfectly compatible with sorting, we will omit them for this lesson. This will allow us to focus solely on sorting problems and mastering them before learning to combine them with filtering.

That said, the setup is the same as at the start of the previous lesson: we have a Todo model with fields task, completed, assignee, priority, and group.

Integrating the OrderingFilter into the API

To enable sorting, we will use the OrderingFilter from the Django REST framework. This filter lets us specify which fields our users can use to sort the data.

First, we need to update our view to include the OrderingFilter. Here's how you do it:

# project/myapp/views.py
from rest_framework.filters import OrderingFilter

class TodoListCreate(generics.ListCreateAPIView):
    queryset = Todo.objects.all()
    serializer_class = TodoSerializer
    filter_backends = [OrderingFilter]
    ordering_fields = ['priority', 'task']  # Specify sortable fields
  • filter_backends = [OrderingFilter]: This line includes the OrderingFilter in our view, allowing us to handle sorting.
  • ordering_fields = ['priority', 'task']: This line specifies the fields by which users can sort the To-Do items, namely by priority and task.

And that’s it! With these small code changes, we've empowered our API with sorting capabilities.

Testing the Sorting Functionality: Setup

First, let’s add some sample To-Do items to test the sorting functionality. We will include a mix of task names to make their sorting more meaningful.

import requests

base_url = 'http://127.0.0.1:8000/api/todos/'

# Example data
todos = [
    {"task": "Buy groceries", "completed": False, "priority": 1, "assignee": "Alice", "group": "Errands"},
    {"task": "Prepare presentation", "completed": True, "priority": 2, "assignee": "Bob", "group": "Work"},
    {"task": "Go to gym", "completed": False, "priority": 3, "assignee": "Charlie", "group": "Health"},
    {"task": "Finish homework", "completed": True, "priority": 1, "assignee": "Alice", "group": "Study"}
]

# Create TODO items
for todo in todos:
    response = requests.post(base_url, json=todo)
    print(f'Created TODO: {response.json()}')
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal