Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django 1.4 Many-to-Many bulk add

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)
like image 711
snakesNbronies Avatar asked Jun 01 '12 06:06

snakesNbronies


2 Answers

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()
like image 100
zzart Avatar answered Sep 25 '22 21:09

zzart


Of course it's possible! You just have to create an explicit intermediate table and then use this model's bulk_create method.

like image 41
rantanplan Avatar answered Sep 25 '22 21:09

rantanplan