How to Add Multiple Objects to ManyToMany Relationship at Once in Django?
Last Updated :
04 Nov, 2024
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.
Many to Many RelationshipNow, 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.
Similar Reads
How to Express a One-To-Many Relationship in Django? In Django, expressing relationships between models is crucial to structuring our database. One of the most common relationships is One-To-Many, where a single record in one model is associated with multiple records in another model. For example, an author can write multiple books, but each book is w
4 min read
CRUD Operation On A Django Model With A Many-to-Many Field Django provides a powerful and flexible way to work with relational databases through its Object-Relational Mapping (ORM). One of the common relationships we encounter in database design is the Many-to-Many relationship. In Django, this relationship is represented using a ManyToManyField.In this art
4 min read
Delete Multiple Objects at Once in Django In Django, deletions of objects are very common once we want to delete outdated information or information we no longer have a need for within our database. Django ORM provides several and efficient ways to delete models instances. To delete instances in Django, we can use either of the following me
3 min read
How to Add Data from Queryset into Templates in Django In this article, we will read about how to add data from Queryset into Templates in Django Python. Data presentation logic is separated in Django MVT(Model View Templates) architecture. Django makes it easy to build web applications with dynamic content. One of the powerful features of Django is fet
3 min read
How to Add Multiple Arguments to Custom Template Filter in a Django Template In Django, template filters are useful for modifying data before displaying it in templates. While built-in filters cover common cases, custom logic is sometimes necessary, particularly when handling multiple arguments.Django only allows one argument to our filter. But we can use different technique
4 min read