0
0
Djangoframework~30 mins

Self-referencing relationships in Django - Mini Project: Build & Apply

Choose your learning style9 modes available
Self-referencing relationships in Django models
📖 Scenario: You are building a simple employee directory for a company. Each employee can have a manager who is also an employee. This means the employee model needs to reference itself to show who manages whom.
🎯 Goal: Create a Django model called Employee that has a self-referencing relationship to represent managers and their team members.
📋 What You'll Learn
Create an Employee model with a name field
Add a self-referencing foreign key called manager to the Employee model
Allow the manager field to be optional (an employee may have no manager)
Use Django's recommended way to reference the same model in the foreign key
Set related_name to team_members for reverse access
💡 Why This Matters
🌍 Real World
Companies often need to model organizational charts where employees report to other employees. This self-referencing relationship helps represent managers and their teams.
💼 Career
Understanding self-referencing models is important for backend developers working with Django to build real-world applications involving hierarchical data.
Progress0 / 4 steps
1
Create the Employee model with a name field
Create a Django model called Employee with a single field name that is a CharField with max length 100.
Django
Need a hint?

Use class Employee(models.Model): and add name = models.CharField(max_length=100).

2
Add a self-referencing foreign key called manager
Add a field called manager to the Employee model. It should be a ForeignKey referencing the Employee model itself using a string, allow null=True and blank=True, and set on_delete=models.SET_NULL.
Django
Need a hint?

Use models.ForeignKey('self', null=True, blank=True, on_delete=models.SET_NULL) for the manager field.

3
Add related_name to the manager field
Modify the manager field to include related_name='team_members' so that you can access an employee's team members via employee.team_members.all().
Django
Need a hint?

Add related_name='team_members' inside the ForeignKey parentheses.

4
Add string representation for Employee
Add a __str__ method to the Employee model that returns the employee's name.
Django
Need a hint?

Define def __str__(self): and return self.name.