Implementing Alphanumeric Data Sorting

Implementing Alphanumeric Data Sorting

Welcome back! In the previous lessons, we set up SQLAlchemy, mapped our Todo model to a database table, and performed CRUD operations. This lesson focuses on enhancing our ToDo application by adding the ability to sort todos.

Sorting is an essential feature in any web application, as it improves user experience by making data easier to navigate and find. Today, we will learn how to implement this functionality step-by-step.

What is Sorting?

Before diving deeper, let's briefly remind ourselves of what sorting is.

Sorting arranges data in a specific order. Common types of sorting include:

  • Alphabetical: Orders data from A-Z (ascending) or Z-A (descending).
  • Numerical: Orders numbers in an ascending (0-9) or descending (9-0) sequence.
  • Alphanumeric: Sorts data containing both letters and numbers, typically placing numbers before letters (e.g., '1 Task', '2 Task', 'Task 1', 'Task 2', 'Task 10').

In this lesson, we will implement alphanumeric sorting by the todo titles to help users find items more quickly.

Implementing Sorting in the Service Layer

Let’s start by updating the get_all method in app/services/todo_service.py to support sorting.

Here’s the updated method:

from models.todo import Todo, db

class TodoService:
    @staticmethod
    def get_all(sort_by=None):
        # Initialize a query on the Todo model
        query = Todo.query
        # Apply sorting if sort_by is 'title'
        if sort_by == 'title':
            query = query.order_by(Todo.title)
        # Execute the query and return all matching todos
        return query.all()

Let's break this down:

  1. Initial Query:
    • We start by initializing a query on the Todo model: query = Todo.query. This sets up a base query to build on.
  2. Sorting:
    • If sort_by is set to 'title', we sort the results: query = query.order_by(Todo.title). This arranges the todos alphanumerically by their titles. If sort_by is anything other than 'title', all items will be fetched without sorting.
  3. Fetching Results:
    • Finally, return query.all() executes the query and returns all matching todos.

Updating the Controller to Handle Sorting

Now, we’ll modify app/controllers/todo_controller.py to capture the sort parameter from the URL and pass it to our updated service method.

Here’s the updated controller:

from flask import Blueprint, render_template, request, redirect, url_for
from services.todo_service import TodoService

todo_service = TodoService()
todo_controller = Blueprint('todo', __name__)

@todo_controller.route('/', methods=['GET'])
def list_todos():
    # Capture sort parameter from the URL
    sort_by = request.args.get('sort_by')
    # Fetch sorted todos
    todos = todo_service.get_all(sort_by=sort_by)
    # Render the todo list template with the todos
    return render_template('todo_list.html', todos=todos)

Let's break this down:

  1. Capturing Parameter:

    • We capture the sort_by parameter from the URL query string using sort_by = request.args.get('sort_by'). This allows us to dynamically read this value whenever a GET request is made to the root route (/).
  2. Fetching Sorted Data:

    • We call todo_service.get_all(sort_by=sort_by) with the captured parameter. This fetches the todos based on the sort criteria specified by the user. If the sort_by parameter is None, the method will return all todos.
  3. Rendering the Template:

    • We render the todo_list.html template with the fetched todos using return render_template('todo_list.html', todos=todos). This passes the sorted list of todos to the template for display.
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