Welcome back! In our previous lesson, we explored how to implement a one-to-one relationship in Django by linking a Note model to an existing Todo model. This relationship allowed each Todo item to have a unique note associated with it.
Today, we will advance to another fundamental concept in database schema design: the one-to-many relationship. This type of relationship is essential in many real-world scenarios, such as associating multiple tasks with a single project or user. By the end of this lesson, you will learn how to define a one-to-many relationship in Django, serialize the data, and perform CRUD (Create, Read, Update, Delete) operations through a REST API.
Let's imagine that we want to store task groups as a separate model to bind more information to a group, such as a group's access rights or settings. In this case, each Group instance can have multiple corresponding Todo instances (as each group stores multiple items), but each Todo instance can be inside only one group. This is called a one-to-many relationship.
Here's how you can define this in models.py:
-
Group Model:
name: A character field to hold the group name.
-
Todo Model:
group: A foreign key to theGroupmodel, establishing a one-to-many relationship. If aGroupis deleted, all the associatedTodotasks will be deleted (on_delete=models.CASCADE). This field can be null or left blank, allowing creation ofTodoinstances without a specified group.
This setup allows each Todo to be associated with one Group, but each Group can have multiple Todos.
In SQL databases, a one-to-many relationship is implemented using a foreign key. The foreign key field in the child table references the primary key of the parent table. In our case, the Todo table has a foreign key referencing the Group table. Here’s an illustration of how these tables might look:
| id | name |
|---|---|
| 1 | Group A |
| 2 | Group B |
| id | task | completed | priority | assignee | group_id |
|---|---|---|---|---|---|
| 1 | Task in group A | False | 1 | 1 | |
| 2 | Another task in A | True | 2 | 1 | |
| 3 | Task in group B | False | 1 | 2 |
Here, we have two tasks (1 and 2) that belong to one group (they both have group_id = 1).
