Introduction to CRUD with Adding To-Dos
Introduction to CRUD Operations
Welcome to the first lesson of our course on implementing an API for a TODO App using Django. In this lesson, we will dive into CRUD operations, which are fundamental building blocks for any web application.
CRUD stands for Create, Read, Update, and Delete. These operations represent the basic actions you can perform on any dataset:
- Create: Adding new entries to the dataset.
- Read: Fetching entries from the dataset.
- Update: Modifying existing entries in the dataset.
- Delete: Removing entries from the dataset.
CRUD operations are vital because they mirror how users interact with applications. Whether you are creating a new blog post, updating your profile, or deleting an email, you are performing CRUD operations.
In this lesson, we'll focus on the first two operations — Create and Read — within the context of a TODO App project.
Recap of Initial Setup
Before we delve into CRUD operations, let's briefly recap the initial setup of our Django project and app. This will ensure we are all on the same page.
We have a Django project and within it, an app called myapp. We also have a model named Todo. Here’s a quick code snippet to remind you of the model setup:
This model has two fields:
task: A character field to store the task description.completed: A boolean field to mark whether the task is completed.
We also have a serializer to convert our model instances to JSON. Here’s a quick code snippet to remind you of the serializer setup:
Including All Fields in Serializer
In the TodoSerializer, we can use fields = '__all__' to include all model fields in the serialized output instead of specifying the list of fields.
You can do it like this:
By setting fields to __all__, we instruct the serializer to include all fields from the Todo model in the serialized output. This is a convenient shortcut when you want to expose all fields of a model in the API response. However, for more control, you can specify individual field names in the fields list, e.g., fields = ['task', 'completed']. In the tasks, we will use both approaches, so you can get comfortable with both.
