How to Implement Many-To-Many Relationship in Django

How do I know if I need a Many-To-Many Relationship instead of a One-To-Many?

Model Relationship 2: Many-To-Many

The Many-to-Many Relationship is confusing. What does it mean?

What is a Many-To-Many Relationship?

Let’s suppose we have two Models: 1) Owner and 2) Dog

The Owner Model might have a name, gender, age, etc… The Dog Model might have breed, name, age, etc…

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

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

For each Model (Owner and Dog) ask yourself, “How many Model X for every Model Y”

For example…

  1. “How many Owners for every Dog?” –> You could have multiple owners for every dog. Each person in the family could be an “owner” (MULTIPLE)
  2. “How many Dogs for every Owner?” –> Each owner, could have more than one dog! (MULTIPLE)

If the answers to 1 question is “MULTIPLE” and the answer to the other question is also “MULTIPLE”, Congratulations! you have a Many-To-Many Relationship.

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

Let’s try to implement the above models:

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

class Dog(models.Model):
     name = models.CharField(max_length=40)
     breed = models.CharField(max_length=30, choices=breeds)
     age = models.IntegerField()
     owners = models.ManyToManyField(Owner)

It really is that simple. However, you might be wondering:

Why is the ManyToManyField on “Dog” and not on “Owner”?

That’s a great question because as you go through this in your own apps, it might not be totally clear.

What is the Heuristic to determining where the ManyToManyField should go?

There isn’t a Heuristic for the ManyToManyField. It hardly makes a difference.

However, try both ways just for practice. You’ll soon realize that it doesn’t matter.

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