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:

# project/myapp/models.py
from django.db import models

class Todo(models.Model):
    task = models.CharField(max_length=200)
    completed = models.BooleanField(default=False)

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:

# project/myapp/serializers.py
from rest_framework import serializers
from .models import Todo

class TodoSerializer(serializers.ModelSerializer):
    class Meta:
        model = Todo
        fields = ['id', 'task', 'completed']

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:

class TodoSerializer(serializers.ModelSerializer):
    class Meta:
        model = Todo
        fields = '__all__'

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.

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