Introduction

In this lesson, we will explore the concept of many-to-many relationships in databases and their implementation in Django. A many-to-many relationship allows multiple records in one table to be associated with multiple records in another table. This type of relationship is crucial for various real-world applications, such as connecting tags to tasks where a single task can have multiple tags and a single tag can be associated with multiple tasks.

By the end of this lesson, you will be able to:

  • Define models in Django that use many-to-many relationships.
  • Create serializers to handle these relationships.
  • Load initial data using fixtures.
  • Write unit tests to verify many-to-many relationships.
Defining Models with Many-to-Many Relationship

Imagine you want to implement adding tags for your todo items. You can add multiple tags to each todo item, and each tag can be added to multiple todo items. This is called a many-to-many relationship.

We'll use two models: Tag and Todo. Each Todo task can have multiple Tags, and each Tag can be associated with multiple Todo tasks. We achieve this in Django using the ManyToManyField.

Here's how we define the Tag and Todo models:

from django.db import models

class Tag(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.CharField(max_length=255, blank=True, null=True)
    tags = models.ManyToManyField(Tag, blank=True)

    def __str__(self):
        return self.task
  • Tag Model: Defines a simple tag with a name.
  • Todo Model: Defines a task with various fields such as task, completed, priority, assignee, and group.
  • tags: A ManyToManyField in the Todo model that links it to the Tag model. This field allows a task to have multiple tags, and a tag can be linked to multiple tasks.
How Many-to-Many Relationship Is Stored in SQL Database

In a relational database, a many-to-many relationship is typically stored using a third table, known as a "junction table" or "join table". This table holds references to the primary keys of the two tables involved in the relationship.

Here’s how the tables would look for the Todo and Tag models:

  • Todo
idtaskcompletedpriorityassigneegroup
1Task with tagsFalse1
2Another taskTrue2
  • Tag
idname
1Urgent
2Home
  • Todo_tags (Junction Table)
idtodo_idtag_id
111
212
321

In the Todo_tags table, each row represents a link between a Todo task and a Tag. For example, the first row shows that the Todo task with id=1 is associated with the Tag with id=1 (Urgent). We see that the first Todo item has tags Urgent and Home, and the second Todo item has tag Urgent.

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