django 1.4 Many-to-Many bulk add

snakesNbronies picture snakesNbronies · Jun 1, 2012 · Viewed 13.9k times · Source

I was wondering if there is the equivalent of a "add all" or "bulk create" for many to many relationships which reduce the number of queries (I will be doing this for a long list)?

The docs on this subject seem to suggest that this is not possible:

https://docs.djangoproject.com/en/dev/topics/db/examples/many_to_many/

**Associate the Article with a Publication:**
a1.publications.add(p1)

**Create another Article, and set it to appear in both Publications:**
a2 = Article(headline='NASA uses Python')
a2.save()
a2.publications.add(p1, p2)
a2.publications.add(p3)

Answer

zzart picture zzart · Jun 6, 2014

If you want to add queryset to bulk add or remove method of many to many relation models :

qs = Article.objects.all()
publications = Publications.objects.get(id=1)

publications.article_set.add(*qs)
publications.save()
publications.article_set.remove(*qs)
publications.save()