Filtering Data Using Initial Characters

Filtering Data Using Initial Characters

Welcome back! In the previous lesson, we added the ability to sort todos in our ToDo application. This lesson focuses on enhancing our application further by adding the ability to filter todos.

Filtering 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 Filtering?

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

Filtering involves displaying only the data that matches certain criteria, effectively hiding the rest. For example, filtering todos by title initial characters allows users to narrow down the list to items that start with specific letters.

In this lesson, we will implement filtering todos based on the initial letters of their titles.

Implementing Filtering in the Service Layer

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

Here’s the updated method:

from models.todo import Todo, db

class TodoService:
    @staticmethod
    def get_all(sort_by=None, filter_by=None):
        # Initialize a query on the Todo model
        query = Todo.query
        # Apply filtering if filter_by is provided
        if filter_by:
            query = query.filter(Todo.title.ilike(f'{filter_by}%'))
        # 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. Filtering:
    • If filter_by is provided, we filter the query: query = query.filter(Todo.title.ilike(f'{filter_by}%')). Let's break down what this does:
    • ilike: This is a method that performs a case-insensitive match. It checks if the data in Todo.title starts with the specified letters (given in filter_by) without worrying about uppercase or lowercase differences.
    • %: This is a wildcard character used in SQL that matches any sequence of characters. In the context of '{filter_by}%', it ensures that any additional characters after filter_by are included. For example, if filter_by is "A", it will match titles like "Apple", "Ascend", etc.
  3. 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.
  4. Fetching Results:
    • Finally, return query.all() executes the query and returns all matching todos.

The order of operations is important here: filtering is applied first, and then sorting. This ensures that we can perform both actions together or each individually based on the provided parameters, making our service layer highly flexible for various user needs.

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