[Django]-Bulk update for many to many fields

22👍

The answer is here:
https://stackoverflow.com/a/10116452/202168

In short, (in Django >= 1.4) you can do a bulk_create on the through model, even if you haven’t defined a custom through model.

10👍

Django – 2.27
Python 3.8

Let filter out the set of books

books = Book.objects.filter(...)

Create a author

author = Author.objects.create(...)

Add related_name for author field in Book model as author_book.

...
author = models.ManyToManyField(null=true, blank=true, related_name="author_book")
...

now add the author into set of books using reverse relation technique.

author.author_book.add(*books)

use * to unpack the query set

Note: we do not need to explicitly call save()

Leave a comment