Introduction
A ForeignKey lets you link one item to many others. It helps organize related data clearly.
Jump into concepts and practice - no test required
A ForeignKey lets you link one item to many others. It helps organize related data clearly.
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.
class Comment(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE)
text = models.TextField()class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True) order_date = models.DateField()
This example shows an Author with many Books. Each Book links to one Author 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=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)
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()).
ForeignKey creates a one-to-many link between models.
It helps keep related data connected and organized.
Remember to choose on_delete behavior carefully.
ForeignKey field to represent a one-to-many relationship?Book that links to a model named Author?on_delete argument to specify delete behavior.on_delete=models.CASCADE. Options A, B, and D have syntax errors or missing required arguments.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)
Book.objects.filter(author__name='Alice').count() return if there are 3 books by Alice and 2 by Bob?class Comment(models.Model):
post = models.ForeignKey(Post)
text = models.TextField()on_delete is required for ForeignKey fields.on_delete, causing an error.class Category(models.Model):
name = models.CharField(max_length=50)
class Product(models.Model):
name = models.CharField(max_length=100)
category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True)