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:
Let's break this down:
- Initial Query:
- We start by initializing a query on the
Todomodel:query = Todo.query. This sets up a base query to build on.
- We start by initializing a query on the
- Filtering:
- If
filter_byis 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 inTodo.titlestarts with the specified letters (given infilter_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 afterfilter_byare included. For example, iffilter_byis "A", it will match titles like "Apple", "Ascend", etc.
- If
- Sorting:
- If
sort_byis set to 'title', we sort the results:query = query.order_by(Todo.title). This arranges the todos alphanumerically by their titles.
- If
- Fetching Results:
- Finally,
return query.all()executes the query and returns all matching todos.
- Finally,
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.
