Open In App

How to Add Multiple Objects to ManyToMany Relationship at Once in Django?

Last Updated : 04 Nov, 2024
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

In Django, the ManyToManyField allows for the creation of relationships where multiple records in one table can be associated with multiple records in another table. Adding multiple objects to a Many-to-Many relationship is a common requirement in web development, especially when dealing with things like tags, categories, or teams.

To add multiple instances to models having ManyToMany relationships, Django Provides two methods:

  • add(*objects)
  • set(list_of_objects)

In this article, we will walk through adding multiple objects to a Many-to-Many relationship at once in Django, covering both methods to achieve this efficiently.

Understanding ManyToMany Relationships

A relationship is said to be many to many if an element of set A can be associated with multiple elements of set B and a single element of set B can be associated with many elements of set A. A common real-life example is that an author can write multiple books and at the same time a book can be written by multiple authors.

m2mrelation
Many to Many Relationship

Now, let's see how can we add multiple instances to ManyToMany fields. For the demonstration purpose, we will use the following models.

models.py

Python
from django.db import models

class Author(models.Model):
    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name

class Book(models.Model):
    title = models.CharField(max_length=200)
    author = models.ManyToManyField(to=Author)

    def __str__(self):
        return self.title

Here, the Book and Author models are related via a many-to-many relationship.

We will be using Django shell a command line to run Django ORM queries to insert data to our tables. Run the command to open Django shell:

python manage.py shell

Firstly, lets create some instances of Author and Book.

Python
# Creating Authors
a1 = Author.objects.create(name="John Doe")
a2 = Author.objects.create(name="Ramesh Kumar")
a3 = Author.objects.create(name="Henry Ford")
a4 = Author.objects.create(name="Mohit Sharma")

# Creating Books
b1 = Book.objects.create(title="Fictional Diary")
b2 = Book.objects.create(title="Encyclopedia")
b3 = Book.objects.create(title="Prehistoric Wildlife Science")
b4 = Book.objects.create(title="Learn Django")

Here, we are creating four instances of Author and four Instances of Book.

Add multiple objects using add()

We can use the add() method to add Authors to a Book or vice versa. Here's how we can add multiples objects. The add method takes any number of objects and performs the update operation.

Python
b1.author.add(a1, a2)
b1.author.all()
# Output: <QuerySet [<Author: John Doe>, <Author: Ramesh Kumar>]>

a3.book_set.add(b1, b2) 
a3.book_set.all()
# Output: <QuerySet [<Book: Fictional Diary>, <Book: Encyclopedia>]>

Here, we have added a1 and a2 authors to book b1 and b1 and b2 books to author a3. Here, to add books to Author we are using book_set to access related objects.

Adding multiple objects using set() method

We can also associate multiple objects to a ManyToManyField of a row using the set() method.

The main difference between add() and set() method is if we try to add more objects in our case more authors to a book, add(object) method will append the object and keep the previous authors intact. Whereas the set(objects) method will remove the previously associated authors with the book and set the new authors passed with the set() method.

We have previously added two authors named "John Doe" and "Ramesh Kumar" to a book named "Fictional Diary". Let's use the set methods to add more authors and books.

Python
b2.author.set([a1, a3, a4]) 
b2.author.all()
# Output: <QuerySet [<Author: John Doe>, <Author: Henry Ford>, <Author: Mohit Sharma>]>

a2.book_set.set([b1, b2, b4])                 
a2.book_set.all()
# Output: <QuerySet [<Book: Fictional Diary>, <Book: Learn Django>, <Book: Encyclopedia>]>

Here, we have set three authors (a1, a3, and a4) to the book (b2) and three books (b1, b2, and b4) to the author (a2).

By using the add() method or the set() method, we can easily add multiple instances of to ManyToManyRelationship in Django. However, it is important to know the differences between them and use the efficient method depending on our requirements.


Next Article
Article Tags :
Practice Tags :

Similar Reads