How to Implement One-To-One Relationship in Django

Posted by Chris Bartos on February 28, 2016

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.

Similar Posts

How to Implement One-To-Many Relationship in Django

Django REST Framework Email Course

You'll get 1 lesson everyday for 7 days.
You'll learn:

  • Serializers
  • Request Methods
  • Endpoints
  • Basic Authentication
  • and more...
Powered by ConvertKit

Django REST Framework Documentation got you down? Just want to get SOMETHING working?

You can learn Django REST Framework in ONE week at about 15 - 30 minutes per day (1 lesson per day for the next 7 days).

Click the button below to sign up and start learning Django REST Framework today!

click here to receive the first lesson in minutes!
(once you sign up, you'll get a new lesson everyday for the next 7 days)

Get some value from this post? Please like and share this post because more people also deserve some value. :-)