How to Implement One-To-One Relationship in Django

How do I implement a One-To-One Relationship and why would I need to?

Model Relationship 3: One-To-One

Why not just put all my data in one model instead of breaking it up? For one thing, it makes your models easier to work with. Let’s look at an example.

What is a One-To-One Relationship?

Let’s suppose you have one model called “Dog”. Your model has the following information:

  • name
  • age
  • gender
  • breed
  • weight
  • etc…

This would be the PERFECT example of a One-To-One Relationship! Why?

How to determine if you have a One-To-One Relationship

What if you wanted to add a Cat Model? You might have:

  • name
  • age
  • gender
  • color
  • outdoor_cat
  • etc…

You don’t want to duplicate fields between models, so you would want to use a One-To-One field. Let’s see what I mean.

How to Implement a One-To-One Relationship in Django

Let’s try to implement the above models:

class Animal(models.Model): name = models.CharField(max_length=45) age = models.IntegerField() gender = models.CharField(max_length=6, choices=genders)

class Dog(models.Model): animal = models.OneToOneField(Animal) breed = models.CharField(max_length=50, choices=breeds) weight = models.IntegerField()

class Cat(models.Model): animal = models.OneToOneField(Animal) color = models.CharField(max_length=20, choices=cat_colors) outdoor_cat = models.BooleanField()

It really is that simple.

Struggle with the Django Documentation?

If this post helped you, sign up for my newsletter and you'll get a new post each week that will help you master Django ABSOLUTELY FREE!

Powered by ConvertKit