0
0
Djangoframework~30 mins

Inline models for related data in Django - Mini Project: Build & Apply

Choose your learning style9 modes available
Inline models for related data
📖 Scenario: You are building a simple Django admin interface for a bookstore. Each Book can have multiple Authors. You want to manage the authors directly on the book's admin page using inline models.
🎯 Goal: Create Django models for Book and Author with a relationship. Then configure the Django admin to show Author as an inline model on the Book admin page.
📋 What You'll Learn
Create a Django model called Book with a title field.
Create a Django model called Author with a name field and a foreign key to Book.
Create an inline admin class for Author using TabularInline.
Register the Book model in the admin with the Author inline.
💡 Why This Matters
🌍 Real World
Managing related data like authors for books directly in the admin page saves time and keeps data organized.
💼 Career
Knowing how to use inline models in Django admin is a common task for backend developers working with Django to build admin interfaces.
Progress0 / 4 steps
1
Create the Book and Author models
Create a Django model called Book with a title field as models.CharField(max_length=100). Also create a Django model called Author with a name field as models.CharField(max_length=50) and a foreign key to Book named book with on_delete=models.CASCADE.
Django
Need a hint?

Use models.CharField for text fields and models.ForeignKey to link Author to Book.

2
Create an inline admin class for Author
In the Django admin file, import admin and create a class called AuthorInline that inherits from admin.TabularInline. Set its model attribute to Author.
Django
Need a hint?

Use admin.TabularInline to create a simple inline table for authors.

3
Create a BookAdmin class with AuthorInline
Create a Django admin class called BookAdmin that inherits from admin.ModelAdmin. Add an attribute inlines and set it to a list containing AuthorInline.
Django
Need a hint?

Set inlines to a list with your inline class inside.

4
Register Book model with BookAdmin
Register the Book model with the Django admin site using admin.site.register(Book, BookAdmin).
Django
Need a hint?

Use admin.site.register to connect your model and admin class.