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 fieldAdd a self-referencing foreign key called
manager to the Employee modelAllow 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