Model Relationships

  • Detailed explanation of Django model relationships and how models connect with each other.
  • What are Model Relationships?

    Model Relationships define how tables are connected to each other in a database.

    Relationships help us avoid:

    • Data duplication

    • Repeated information

    • Complex SQL joins

    Real-World Example

    Entity

    Relationship

    User → Profile

    One-to-One

    Category → Products

    One-to-Many

    Students ↔ Courses

    Many-to-Many

    ONE-TO-ONE RELATIONSHIP

    Concept Explanation

    • One record in table A is linked to only one record in table B

    • Used when data is split for clarity

    Example:
    One User → One Profile

One-to-One Relationship Example

Each user has exactly one profile.

from django.db import models
from django.contrib.auth.models import User

class Profile(models.Model):
    user = models.OneToOneField(
        User,
        on_delete=models.CASCADE
    )
    phone = models.CharField(max_length=15)
    address = models.TextField()

    def __str__(self):
        return self.user.username
  • How It Works

    • OneToOneField creates a unique relationship

    • on_delete=models.CASCADE deletes profile if user is deleted

ORM Usage Example

user = User.objects.get(username="hinal")
print(user.profile.phone)
  • ONE-TO-MANY RELATIONSHIP

    Concept Explanation

    • One record in table A → many records in table B

    • Implemented using ForeignKey

    Example:
    One Category → Many Products

One-to-Many Relationship Example

Each product belongs to one category.

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

    def __str__(self):
        return self.name

class Product(models.Model):
    category = models.ForeignKey(
        Category,
        on_delete=models.CASCADE
    )
    name = models.CharField(max_length=100)
    price = models.FloatField()

    def __str__(self):
        return self.name
  • How It Works

    • ForeignKey creates one-to-many

    • Many products → one category

ORM Usage Example

category = Category.objects.get(name="Electronics")
products = category.product_set.all()
  • product_set is auto-generated by Django.

    MANY-TO-MANY RELATIONSHIP

    Concept Explanation

    • Many records in table A → many records in table B

    • Uses a junction table

    Example:
    Students ↔ Courses

Many-to-Many Relationship Example

A student can enroll in multiple courses.

class Course(models.Model):
    name = models.CharField(max_length=100)
    def __str__(self):
        return self.name

class Student(models.Model):
    name = models.CharField(max_length=100)
    courses = models.ManyToManyField(Course)
    def __str__(self):
        return self.name
  • How It Works

    • Django creates an automatic intermediate table

    • No need to write SQL joins

ORM Usage Example

student = Student.objects.get(name="Hinal")
course = Course.objects.get(name="Django")

student.courses.add(course)

Fetch Related Data

student.courses.all()
course.student_set.all()
  •  Comparison Table 

    Relationship

    Field Used

    Example

    One-to-One

    OneToOneField

    User → Profile

    One-to-Many

    ForeignKey

    Category → Product

    Many-to-Many

    ManyToManyField

    Student ↔ Course

  •  on_delete Options (Important)

    Option

    Meaning

    CASCADE

    Delete related records

    SET_NULL

    Set field to NULL

    PROTECT

    Prevent deletion

    SET_DEFAULT

    Set default value


Blog App Relationships

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

class Post(models.Model):
    author = models.ForeignKey(Author, on_delete=models.CASCADE)
    title = models.CharField(max_length=200)
    tags = models.ManyToManyField('Tag')


class Tag(models.Model):
    name = models.CharField(max_length=50)