0
0
Djangoframework~30 mins

Through model for extra fields on M2M in Django - Mini Project: Build & Apply

Choose your learning style9 modes available
Through model for extra fields on M2M
📖 Scenario: You are building a simple Django app to manage books and authors. Each book can have multiple authors, and each author can write multiple books. You want to store extra information about the relationship, such as the role of the author for that book (e.g., 'Writer', 'Editor').
🎯 Goal: Create a Django many-to-many relationship between Book and Author models using a through model to store the extra field role. This will allow you to track the role of each author on each book.
📋 What You'll Learn
Create Author and Book models with basic fields
Create a BookAuthor through model with a role field
Set up the many-to-many field on Book using the through model
Demonstrate adding authors to books with roles
💡 Why This Matters
🌍 Real World
Many real-world apps need to store extra data about relationships, like roles of people in projects or tags with metadata.
💼 Career
Understanding through models is essential for Django developers to handle complex many-to-many relationships with extra fields.
Progress0 / 4 steps
1
Create the basic Author and Book models
Create two Django models: Author with a name field as models.CharField(max_length=100), and Book with a title field as models.CharField(max_length=200). Do not add any relationships yet.
Django
Need a hint?

Use models.CharField for text fields with max_length.

2
Create the BookAuthor through model with a role field
Create a new model called BookAuthor with three fields: book as a ForeignKey to Book, author as a ForeignKey to Author, and role as a models.CharField(max_length=50) to store the author's role on the book.
Django
Need a hint?

Use ForeignKey with on_delete=models.CASCADE for relations.

3
Add the many-to-many field on Book using the through model
In the Book model, add a many-to-many field called authors that links to Author using the BookAuthor model as the through argument.
Django
Need a hint?

Use models.ManyToManyField with the through parameter set to the through model name as a string.

4
Add example code to create a book with authors and roles
Write example code to create an Author named 'Jane Doe', a Book titled 'Django Basics', and then create a BookAuthor instance linking them with the role 'Writer'.
Django
Need a hint?

Use Model.objects.create() to create instances and link them via the through model.