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.
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:
task: This field is aCharField, which is used to store text data. Note thatCharFieldmust have amax_lengthparameter. We set themax_lengthto 200, which means this field can store up to 200 characters.completed: This field is aBooleanFieldthat stores aTrueorFalsevalue. We set the default value toFalse, 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 thetask.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:
| id | task | completed |
|---|---|---|
| 1 | Example Task 1 | False |
| 2 | Example Task 2 | True |
