one-to-many relationship in Django Model

In Django, a one-to-many relationship is typically represented using a ForeignKey field in the model. This allows each instance of the model to be associated with one instance of another model. Here’s an example to illustrate this:

Let’s say you have two models: Author and Book. Each author can write multiple books, but each book is written by only one author. This is a one-to-many relationship from Author to Book.

Here’s how you can define these models in Django:

from django.db import models

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

    def __str__(self):
        return self.name

class Book(models.Model):
    title = models.CharField(max_length=200)
    publication_date = models.DateField()
    author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='books')

    def __str__(self):
        return self.title

Explanation:

  1. Author Model:
    • name: A CharField to store the author’s name.
    • birth_date: A DateField to store the author’s birth date.
    • __str__: A method to return the author’s name when the model instance is printed.
  2. Book Model:
    • title: A CharField to store the book’s title.
    • publication_date: A DateField to store the book’s publication date.
    • author: A ForeignKey field that creates a many-to-one relationship. Each book is associated with one author.
      • on_delete=models.CASCADE: This means that when the referenced author is deleted, all their books will be deleted as well.
      • related_name='books': This allows you to access all books written by a specific author using author.books.all().

Usage:

To create an author and some books, you might do something like this in the Django shell or a view:

# Creating an author
author = Author.objects.create(name="Jane Austen", birth_date="1775-12-16")

# Creating books for the author
Book.objects.create(title="Pride and Prejudice", publication_date="1813-01-28", author=author)
Book.objects.create(title="Sense and Sensibility", publication_date="1811-10-30", author=author)

# Accessing books written by an author
jane_austen_books = author.books.all()
for book in jane_austen_books:
    print(book.title)

This setup ensures that each book is linked to one author, and you can easily retrieve all books written by a particular author using the related_name specified in the ForeignKey field.