Introduction

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.

Model Design for One-to-Many Relationship

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:

from django.db import models

class Group(models.Model):
    name = models.CharField(max_length=255)

    def __str__(self):
        return self.name

class Todo(models.Model):
    task = models.CharField(max_length=255)
    completed = models.BooleanField(default=False)
    priority = models.IntegerField()
    assignee = models.CharField(max_length=255, blank=True, null=True)
    group = models.ForeignKey(Group, on_delete=models.CASCADE, null=True, blank=True)

    def __str__(self):
        return self.task
  1. Group Model:

    • name: A character field to hold the group name.
  2. Todo Model:

    • group: A foreign key to the Group model, establishing a one-to-many relationship. If a Group is deleted, all the associated Todo tasks will be deleted (on_delete=models.CASCADE). This field can be null or left blank, allowing creation of Todo instances without a specified group.

This setup allows each Todo to be associated with one Group, but each Group can have multiple Todos.

One-to-Many Relationship in SQL

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:

idname
1Group A
2Group B
idtaskcompletedpriorityassigneegroup_id
1Task in group AFalse11
2Another task in ATrue21
3Task in group BFalse12

Here, we have two tasks (1 and 2) that belong to one group (they both have group_id = 1).

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