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.

Similar Posts

What do you do when 'makemigrations' is telling you About your Lack of Default Value
Test your Queries before they make it into Production using the Django Shell
I have a ChoiceField Callable that Includes a Queryset but it Breaks my Django app
Simple Method of Updating Models with ModelForms
How to filter a DateTimeField by today's date in Django

Need help with Django REST Framework? Django REST Framework documentation a little confusing?

Join me for my FREE Django REST Framework email course:

Django REST Framework Email Course

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

  • Serializers
  • Request Methods
  • Endpoints
  • Basic Authentication
  • JQuery Integration
  • AngularJS Integration
Powered by ConvertKit