0
0
Djangoframework~5 mins

ForeignKey for one-to-many in Django

Choose your learning style9 modes available
Introduction

A ForeignKey lets you link one item to many others. It helps organize related data clearly.

You want to connect many comments to one blog post.
You need to link multiple orders to one customer.
You want to assign many books to one author.
You want to track many tasks under one project.
Syntax
Django
class ModelName(models.Model):
    field_name = models.ForeignKey(OtherModel, on_delete=models.CASCADE)

OtherModel is the model you link to.

on_delete=models.CASCADE means if the linked item is deleted, related items are deleted too.

Examples
Each comment links to one post. If the post is deleted, its comments are deleted.
Django
class Comment(models.Model):
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    text = models.TextField()
Orders link to customers. If a customer is deleted, orders keep a null customer instead of deleting.
Django
class Order(models.Model):
    customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True)
    order_date = models.DateField()
Sample Program

This example shows an Author with many Books. Each Book links to one Author using ForeignKey.

Django
from django.db import models

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

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

# Example usage in Django shell:
# author = Author.objects.create(name='Jane Doe')
# book1 = Book.objects.create(title='Book One', author=author)
# book2 = Book.objects.create(title='Book Two', author=author)
# print(book1.author.name)
# print(book2.author.name)
OutputSuccess
Important Notes

Always set on_delete to decide what happens when the linked item is removed.

You can access all related items from the linked model using modelname_set by default (e.g., author.book_set.all()).

Summary

ForeignKey creates a one-to-many link between models.

It helps keep related data connected and organized.

Remember to choose on_delete behavior carefully.