0
0
Djangoframework~30 mins

Related name for reverse access in Django - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Related Name for Reverse Access in Django Models
📖 Scenario: You are building a simple blog application where each Author can have multiple Post entries. You want to access all posts written by an author easily from the author object.
🎯 Goal: Create two Django models, Author and Post, where Post has a foreign key to Author with a related_name set. This will allow reverse access from an author to their posts using the related name.
📋 What You'll Learn
Create a Django model called Author with a name field
Create a Django model called Post with a title field
Add a foreign key in Post to Author with related_name='posts'
Use the related_name to access all posts of an author
💡 Why This Matters
🌍 Real World
In many web applications, you need to model relationships between data, such as authors and their posts. Using related_name makes it easy to navigate these relationships in your code.
💼 Career
Understanding Django model relationships and reverse access is essential for backend developers working with Django to build scalable and maintainable web applications.
Progress0 / 4 steps
1
Create the Author model
Create a Django model called Author with a single field name which is a CharField with max length 100.
Django
Need a hint?

Use models.CharField(max_length=100) for the name field.

2
Create the Post model with foreign key to Author
Create a Django model called Post with a title field as CharField max length 200, and add a foreign key field called author to the Author model with related_name='posts'.
Django
Need a hint?

Use models.ForeignKey with on_delete=models.CASCADE and related_name='posts'.

3
Access posts from an author using related_name
Write a Django ORM query to get all posts of an Author instance stored in variable author using the related_name posts. Assign the result to a variable called author_posts.
Django
Need a hint?

Use the related_name posts on the author instance to get all posts.

4
Add __str__ methods for better display
Add a __str__ method to both Author and Post models that return the name and title fields respectively.
Django
Need a hint?

Define __str__ methods returning the main identifying field for each model.