Creating a one-to-one relationship
Step 1: Define Your Models
First, we need to define two models. We'll create a Contact
model and an Employee
model. Each Employee
will have a unique Contact
.
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 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)
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 Employee
data, including their Contact
information.
views.py
from django.shortcuts import render, get_object_or_404
from .models import Employee
def employee_detail(request, employee_id):
employee = get_object_or_404(Employee, id=employee_id)
return render(request, 'employee_detail.html', {'employee': employee})
def employee_list(request):
employees = Employee.objects.all()
return render(request, 'employee_list.html', {'employees': employees})
Step 3: Define URLs to Access Views
We'll add URLs to access the list of employees and their details.
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('employee/<int:employee_id>/', views.employee_detail, name='employee_detail'),
path('employees/', views.employee_list, name='employee_list'),
]
Step 4: Create Templates for Display
We'll create templates to beautifully display our data.
templates/employee_detail.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Employee Detail</title>
</head>
<body>
<h1>Employee Detail</h1>
<h2>{{ employee.first_name }} {{ employee.last_name }}</h2>
<p> Phone: {{ employee.contact.phone }}</p>
<p>Address: {{ employee.contact.address }}</p>
<a href="{% url 'employee_list' %}">Back to Employee List</a>
</body>
</html>
templates/employee_list.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Employee List</title>
</head>
<body>
<h1>Employee List</h1>
<ul>
{% for employee in employees %}
<li>
<a href="{% url 'employee_detail' employee.id %}">
{{ employee.first_name }} {{ employee.last_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
admin.site.register(Employee)
admin.site.register(Contact)
Wrapping Up 🎁
You've now created a one-to-one relationship in Django and displayed the data using beautiful templates. Keep exploring Django to build more powerful and dynamic web applications!