How to Implement Many-To-Many Relationship in Django

Posted by Chris Bartos on February 27, 2016

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.

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. :-)