ForeignKey Relationship Example
A snippet showing how to set up a ForeignKey in Django models.
# models.py
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='books')
def __str__(self):
return self.title
# Django Shell
>>> from library.models import Author, Book
>>> author = Author.objects.create(name='J.K. Rowling')
>>> book = Book.objects.create(title='Harry Potter', author=author)
>>> book.author.name
'J.K. Rowling'
>>> author.books.all()
<QuerySet [<Book: Harry Potter>]>
Explanation:
-
ForeignKeycreates a one-to-many relationship between two models (e.g., one author can have many books). -
on_delete=models.CASCADEensures that if the author is deleted, their books are also deleted. -
The
related_nameattribute lets you access all related objects (e.g.,author.books.all()). - This pattern is common for blogs (Author → Posts), shops (Category → Products), etc.
- Category Models & ORM
- Total Views 1111
- Last Modified 17 September, 2025
- Tags #models #relationships #foreignkey #orm
Previous snippet
Set Default Value in Model Field
Next snippet