Database Relationships in Django

Short visual memo for the three ways to define database relationships in Django.

Many-to-One

Many-to-One database relationship

class Employee(models.Model):
    department = models.ForeignKey(Department, on_delete=models.CASCADE)
  • each Employee only has one Department
  • but a Department has multiple Employees
employee.department.pk
department.employee_set.all()

Many-to-Many

Many-to-Many database relationship

class Employee(models.Model):
    projects = models.ManyToManyField(Project)
  • each Employee works on multiple Projects
  • each Project can be worked on by multiple Employees
employee.projects.all()
projects.employee_set.all()

To query the intermediary table:

employee.projects.through.objects.all()
projects.employee_set.through.objects.all()

One-to-One

One-to-One database relationship

class Employee(models.Model):
    resume = models.OneToOneField(Resume, on_delete=models.CASCADE)
  • each Employee only has one Resume
  • each Resume is owned by only one Employee
employee.resume.pk
resume.employee.pk

Sources

Avant TVA et autoliquidation

Tag Kemar Joint