Django / Django Models

Creating One-to-One, One-to-Many, and Many-to-Many Relationships

This tutorial explores how to create relationships between Django models. This includes One-to-One, One-to-Many, and Many-to-Many relationships.

Tutorial 2 of 5 5 resources in this section

Section overview

5 resources

Explores Django models, including defining models, relationships, and model queries.

1. Introduction

In this tutorial, we'll explore how to create relationships between Django models. We will cover the three types of relationships: One-to-One, One-to-Many, and Many-to-Many.

What you will learn:
- Understanding Django model relationships
- How to create One-to-One relationships
- How to create One-to-Many relationships
- How to create Many-to-Many relationships

Prerequisites:
- Basic understanding of Python
- Knowledge of Django basics
- Django installed on your system

2. Step-by-Step Guide

Django allows you to define relationships between models in three ways: One-to-One, One-to-Many, and Many-to-Many.

  • One-to-One: For each record in the parent table, there is one and only one record in the child table.
  • One-to-Many: For each record in the parent table, there can be multiple records in the child table.
  • Many-to-Many: Records in the parent table can relate to multiple records in the child table and vice versa.

3. Code Examples

3.1 One-to-One Relationship

In Django, a One-to-One relationship can be defined using OneToOneField.

from django.db import models

class User(models.Model):
    name = models.CharField(max_length=100)

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    bio = models.TextField()

In the example above, we've created a One-to-One relationship between User and Profile. Each User can have one Profile, and each Profile is related to one User.

3.2 One-to-Many Relationship

In Django, a One-to-Many relationship can be created using ForeignKey.

from django.db import models

class Author(models.Model):
    name = models.CharField(max_length=100)

class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.ForeignKey(Author, on_delete=models.CASCADE)

In this example, we've created a One-to-Many relationship between Author and Book. An Author can write multiple Books, but each Book has one Author.

3.3 Many-to-Many Relationship

In Django, a Many-to-Many relationship is created using ManyToManyField.

from django.db import models

class Student(models.Model):
    name = models.CharField(max_length=100)

class Course(models.Model):
    name = models.CharField(max_length=100)
    students = models.ManyToManyField(Student)

In this example, we've created a Many-to-Many relationship between Student and Course. A Student can enroll in multiple Courses, and a Course can have multiple Students.

4. Summary

We learned how to create One-to-One, One-to-Many, and Many-to-Many relationships in Django. These relationships allow us to create complex database schemas to represent real-world relationships between entities.

5. Practice Exercises

Exercise 1: Create a One-to-One relationship between Person and License. Each Person can have one License, and each License belongs to one Person.

Exercise 2: Create a One-to-Many relationship between Teacher and Student. A Teacher can have multiple Students, but each Student has one Teacher.

Exercise 3: Create a Many-to-Many relationship between Actor and Movie. An Actor can be in multiple Movies, and a Movie can have multiple Actors.

Solutions

  1. One-to-One relationship between Person and License.
class Person(models.Model):
    name = models.CharField(max_length=100)

class License(models.Model):
    number = models.CharField(max_length=15)
    person = models.OneToOneField(Person, on_delete=models.CASCADE)
  1. One-to-Many relationship between Teacher and Student.
class Teacher(models.Model):
    name = models.CharField(max_length=100)

class Student(models.Model):
    name = models.CharField(max_length=100)
    teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE)
  1. Many-to-Many relationship between Actor and Movie.
class Actor(models.Model):
    name = models.CharField(max_length=100)

class Movie(models.Model):
    title = models.CharField(max_length=100)
    actors = models.ManyToManyField(Actor)

Continue your learning by exploring different types of relationships and how they can be used in more complex models.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Color Palette Generator

Generate color palettes from images.

Use tool

PDF Splitter & Merger

Split, merge, or rearrange PDF files.

Use tool

Date Difference Calculator

Calculate days between two dates.

Use tool

Interest/EMI Calculator

Calculate interest and EMI for loans and investments.

Use tool

Image Compressor

Reduce image file sizes while maintaining quality.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help