0
0
Djangoframework~5 mins

Model relationships preview in Django

Choose your learning style9 modes available
Introduction

Model relationships let you connect data tables in Django. This helps organize and link related information easily.

You want to link a blog post to its author.
You need to connect products to categories in a store.
You want to track which users liked which comments.
You want to store orders linked to customers.
You want to create a many-to-many connection like students and courses.
Syntax
Django
class ModelName(models.Model):
    foreign_key_field = models.ForeignKey(OtherModel, on_delete=models.CASCADE)
    one_to_one_field = models.OneToOneField(OtherModel, on_delete=models.CASCADE)
    many_to_many_field = models.ManyToManyField(OtherModel)

ForeignKey creates a many-to-one link.

OneToOneField creates a one-to-one link.

ManyToManyField creates a many-to-many link.

Examples
Each book links to one author. Many books can have the same author.
Django
class Author(models.Model):
    name = models.CharField(max_length=100)

class Book(models.Model):
    author = models.ForeignKey(Author, on_delete=models.CASCADE)
    title = models.CharField(max_length=200)
Each user has exactly one profile linked one-to-one.
Django
class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    bio = models.TextField()
Students and courses have a many-to-many relationship.
Django
class Student(models.Model):
    name = models.CharField(max_length=100)

class Course(models.Model):
    students = models.ManyToManyField(Student)
    title = models.CharField(max_length=200)
Sample Program

This example shows a book linked to an author using ForeignKey. When you print book.author.name, it shows the author's name.

Django
from django.db import models

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

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

# Usage example (in Django shell):
# author = Author.objects.create(name='Alice')
# book = Book.objects.create(author=author, title='Django Basics')
# print(book.author.name)
OutputSuccess
Important Notes

Always set on_delete to decide what happens if the linked object is deleted.

Use related_name to customize reverse lookups.

Remember to run migrations after changing models.

Summary

Model relationships connect data tables in Django.

ForeignKey is many-to-one, OneToOneField is one-to-one, ManyToManyField is many-to-many.

They help organize and access related data easily.