Introduction

Welcome to the lesson on creating the To-Do model in Django. In this lesson, we will focus on building the foundational model for our To-Do application. The goal is to help you understand how to define a model in Django, set up corresponding views, and map these views to URLs so that you can create and display To-Do items via an API endpoint.

Models in Django are used to define the structure of your database tables. By the end of this lesson, you will be able to create a Todo model with fields for the task description and its completion status and expose this data through an API that you can test.

Creating the To-Do Model

In Django, a model defines the structure of your database tables. Each model is a Python class that subclasses django.db.models.Model. It contains fields that represent the columns of the table. Let's create our Todo model.

Here is the code for creating the basic Todo model in models.py:

from django.db import models

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

    def __str__(self):
        return self.task
  • task: This field is a CharField, which is used to store text data. Note that CharField must have a max_length parameter. We set the max_length to 200, which means this field can store up to 200 characters.
  • completed: This field is a BooleanField that stores a True or False value. We set the default value to False, meaning that a task is not completed by default.
  • __str__(self): This method returns the model's string representation. It is used when you print an instance of the model, or when the instance is displayed in the Django admin interface or Django shell. As we won't need it in the first courses of this path, we define it as simply the task.name. However, in your project, you can come up with any __str__ method behaviour you find comfortable.

This model represents an SQL table for storing tasks. The columns of this table will be id, task, and completed. Note that we don't need to define the id column manually, Django will create it automatically.

Here is an illustration of how the SQL table would look:

idtaskcompleted
1Example Task 1False
2Example Task 2True
Common Field Types in Django Models
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