Reverse Relationships
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)
# Create authors
author1 = Author.objects.create(name="J.K. Rowling")
author2 = Author.objects.create(name="George Orwell")
# Create books by associating them with authors
book1 = Book.objects.create(title="Harry Potter and the Sorcerer's Stone", author=author1)
book2 = Book.objects.create(title="1984", author=author2)
book3 = Book.objects.create(title="Harry Potter and the Chamber of Secrets", author=author1)
# Access books by a specific author using the reverse relationship
books_by_rowling = author1.book_set.all()
# Print the titles of books by J.K. Rowling
for book in books_by_rowling:
print(f"Book by J.K. Rowling: {book.title}")
Last updated