Creating a one-to-Many relationship
Step 1: Define Your Models
We'll define three models: Contact
, Department
, and Employee
. Each Employee
will have a unique Contact
and belong to a Department
.
models.py
from django.db import models
class Contact(models.Model):
phone = models.CharField(max_length=50, unique=True)
address = models.CharField(max_length=50)
def __str__(self):
return self.phone
class Department(models.Model):
name = models.CharField(max_length=255)
description = models.TextField(null=True, blank=True)
def __str__(self):
return self.name
class Employee(models.Model):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
contact = models.OneToOneField(Contact, on_delete=models.CASCADE, null=True)
department = models.ForeignKey(Department, on_delete=models.CASCADE)
def __str__(self):
return f'{self.first_name} {self.last_name}'
Step 2: Create Views to Display Data π
Next, we'll create views to display our Department
and Employee
data.
views.py
from django.shortcuts import render, get_object_or_404
from .models import Department, Employee
def department_detail(request, department_id):
department = get_object_or_404(Department, id=department_id)
employees = department.employee_set.all() # Access related employees
return render(request, 'department_detail.html', {'department': department, 'employees': employees})
def department_list(request):
departments = Department.objects.all()
return render(request, 'department_list.html', {'departments': departments})
Step 3: Define URLs to Access Views π
We'll add URLs to access the list of departments and their details.
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('department/<int:department_id>/', views.department_detail, name='department_detail'),
path('departments/', views.department_list, name='department_list'),
]
Step 4: Create Templates for Display π¨
We'll create templates to beautifully display our data.
templates/department_detail.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Department Detail</title>
</head>
<body>
<h1>Department Detail</h1>
<h2>{{ department.name }}</h2>
<p>{{ department.description }}</p>
<ul>
{% for employee in employees %}
<li>{{ employee.first_name }} {{ employee.last_name }}</li>
{% endfor %}
</ul>
<a href="{% url 'department_list' %}">π Back to Department List</a>
</body>
</html>
templates/department_list.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Department List</title>
</head>
<body>
<h1>Department List</h1>
<ul>
{% for department in departments %}
<li>
<a href="{% url 'department_detail' department.id %}">
{{ department.name }}
</a>
</li>
{% endfor %}
</ul>
</body>
</html>
Step 5: Register Models in Admin Panel π οΈ
Finally, we'll register our models in the admin panel to manage them easily.
admin.py
from django.contrib import admin
from .models import Employee, Contact, Department
admin.site.register(Employee)
admin.site.register(Contact)
admin.site.register(Department)
Wrapping Up π
You've now created a one-to-many relationship in Django and displayed the data using beautiful templates. Keep exploring Django to build more powerful and dynamic web applications