Welcome back! In our previous lessons, we set up SQLAlchemy and configured our database. We also transitioned our Todo model from in-memory storage using a list to persistent storage with SQLAlchemy.
In this lesson, we will update our TodoService class to perform CRUD operations using SQLAlchemy. CRUD stands for Create, Read, Update, and Delete, and these operations are fundamental for managing data in any application.
By the end of this lesson, you'll adapt your existing TodoService methods to interact with the database, making your app more functional and responsive to user actions.
Let's update the TodoService class, which will now serve as an intermediary between our database and the rest of our application, ensuring clean and maintainable code.
Here's what we will do:
- Retrieve Todos from the Database: We'll update the methods to fetch all
Todoitems and a specificTodoby its ID from the database. - Add Todos to the Database: We'll modify the method to create and persist new
Todoitems in the database. - Update Todos in the Database: We'll adjust the method to update existing
Todoitems and save the changes. - Delete Todos from the Database: We'll refactor the method to remove
Todoitems from the database.
By the end of this section, your TodoService class will be fully integrated with SQLAlchemy, allowing your application to leverage the power of a relational database for persistent storage.
Before diving into the new methods, let's recap how our old TodoService class managed Todo items using in-memory storage with a list:
This implementation worked well for in-memory data but didn't persist any changes.
Let's now transition our methods to utilize SQLAlchemy for database operations.
We are also making the methods static. Since the methods don't rely on instance-specific data (like an instance variable) and act more like utility functions, using static methods can simplify the method calls from other parts of our application.
In the previous implementation, we needed an instance of TodoService because the _todos list was tied to the instance. Now, the database is a shared resource, so static methods are more appropriate.
We start with the most basic operations: retrieving all Todo items and fetching a specific Todo item by its ID.
Explanation:
Todo.query.all(): This line retrieves all rows from theTodotable in the database. It converts each row into an instance of theTodomodel and returns them as a list.Todo.query.get(todo_id): This line retrieves a specificTodoentry by its primary key (ID). If theTodowith the specifiedtodo_idexists, it returns the correspondingTodoobject; otherwise, it returnsNone.
These methods use SQLAlchemy's query interface, which provides a simple yet powerful way to interact with the database. By calling these methods, we can easily fetch data stored in our database, making our application capable of displaying and managing persistent data.
Next, let's look at how to create and add new Todo items to our database.
Explanation:
- Creating a new
Todoinstance:new_todo = Todo(title=title, description=description)initializes a newTodoobject with the providedtitleanddescription. - Adding to session:
db.session.add(new_todo)stages the newTodoobject for insertion into the database. Think of this as adding the new object to a queue of database operations. - Committing the session:
db.session.commit()finalizes and applies all staged changes to the database. This ensures the newTodois actually saved.
By committing the session, we ensure that the new data is persisted in the database. This is crucial for making sure our data changes are saved.
Let’s see how we can update existing Todo items.
Explanation:
- Retrieving the
Todoinstance:todo = TodoService.get_by_id(todo_id)fetches theTodoobject from the database. This object is connected to the database through SQLAlchemy's session. - Modifying fields: Changing
todo.title = titleandtodo.description = descriptionupdates the instance but also signals to SQLAlchemy that these fields should be updated in the database. - Committing the session:
db.session.commit()saves all changes made to any managed objects in this session to the database. This is the step that makes sure your updates are actually stored in the database.
So even though it looks like we're just updating a local instance, these changes are tracked by SQLAlchemy and saved to the database once we commit the session.
Finally, let’s implement the functionality to delete Todo items.
Explanation:
- Retrieving the
Todoinstance:todo = TodoService.get_by_id(todo_id)fetches theTodoobject that you want to delete by its ID. - Marking for deletion:
db.session.delete(todo)marks theTodoobject for deletion from the database. - Committing the session:
db.session.commit()finalizes the deletion, ensuring that theTodois permanently removed from the database.
In this lesson, we've covered how to perform CRUD operations using SQLAlchemy in our Flask application:
- Create: Adding new
Todoitems to the database. - Read: Fetching all
Todoitems or a specific item by its ID. - Update: Modifying existing
Todoitems. - Delete: Removing
Todoitems from the database.
Understanding these operations is crucial for developing dynamic and data-driven applications. Now it’s time for you to practice what you’ve learned. Head over to the practice exercises to solidify your understanding and gain hands-on experience with CRUD operations in SQLAlchemy.
